简体   繁体   中英

Take elements from items in a list of strings

From a given list, take an element from each item to spell a new word.

list1=["whiff", "dog", "axe"]
letters=[]
for j in list1:
    for k in j:
        letters.append(k)

answer = letters[4] + letters[6] + letters[9]

Is there a way to make it simpler than what I've come up with so far? Particularly, is there a way to call an element of an item in a list, and not the entire item itself? I don't want list1[0] for "whiff" , I just want the "f" part of it.

...is there a way to call an element of an item in a list, and not the entire item itself?

Well, you can chain the subscript operators, with something like this...

>>> l = ["whiff", "dog", "axe"]
>>> answer = l[0][4] + l[1][1] + l[2][1]
>>> print answer
fox

With operator.itemgetter :

from operator import itemgetter

list1 = ["whiff", "dog", "axe"]

indexes = [4, 6, 9]
getter = itemgetter(*indexes)
print(getter(''.join(list1))) # prints ('f', 'o', 'x')

If you do want to have access to a list of all letters in all words you could use:

>>> list1=["whiff", "dog", "axe"]
>>> from itertools import chain
>>> all_letters = list(chain(*list1))
>>> all_letters
['w', 'h', 'i', 'f', 'f', 'd', 'o', 'g', 'a', 'x', 'e']
>>> answer = all_letters[4] + all_letters[6] + all_letters[9]

chain produces a concatenation of all iterables it gets as arguments - strings are iterable, too. I need to call list on its result as it only returns an iterator.

Then we have one long list, without the need to write a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM