简体   繁体   English

从字符串列表中的项目中获取元素

[英]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. 我不希望list1[0]代表"whiff" ,我只想要它的"f"部分。

...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 : 使用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. chain生成它作为参数获取的所有迭代的串联 - 字符串也是可迭代的。 I need to call list on its result as it only returns an iterator. 我需要在其结果上调用list ,因为它只返回一个迭代器。

Then we have one long list, without the need to write a loop. 然后我们有一个长列表,而不需要编写循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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