Java, Python, Quick solutions, Uncategorized

How to solve: pick elements from one list, that indexes are stored in second list

Today I am going to show you how to create a list combined with those elements from one list, that have indexes collected in the second list. For my example I will use python, because I have a little contact with it recently at my work.

def main():
    x = ['a', 'b', 'c', 'd', 'e']
    y = [1, 2, 3]
    z = [x[_] for _ in y]
    print(z)


if __name__ == "__main__":
    main()

Script presented above solves exactly the issue, which was presented in the topic.  You may ask, what underscore (‘_’) sign means in this case. It represents each and every element in the list and helps to iterate over them without necessity of describing it in a direct way. It can be substituted with another variable crated in place by parser. The same thing is achieved in stream API of Java 8 with lambdas, but single underscore sign is not allowed it this case:

IntStream.range(1, 4).map(_a -> _a * 2).forEach(System.out::print);

Python code should print list containing three elements like below:

[‘b’, ‘c’, ‘d’]

Advertisements

One thought on “How to solve: pick elements from one list, that indexes are stored in second list

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s