简体   繁体   English

如何解压缩列表元组

[英]How to unpack a tuple of lists

I am attempting to unpack the elements of a list that is packed inside a tuple. 我试图解压缩包含在元组内的列表的元素。

myTuple = (['a', 'list', 'of', 'strings'], ['inside', 'a', 'tuple'], ['extra', 'words', 'for', 'filler'])

So for example I want to get this element ('a') 所以例如我想得到这个元素('a')

I have tried this: 我试过这个:

for (i, words) in list(enumerate(myTuple)):
    print(words)

But this returns the list like this 但是这会像这样返回列表

['a', 'list', 'of', 'strings']
['inside', 'a', 'tuple']
etc...

How can I get the elements inside the list? 如何获取列表中的元素?

You can use the indexing of your tuple and then the lists to access the inner-most elements. 您可以使用元组的索引,然后使用列表来访问最内层的元素。 For example, to get at the string 'a' , you could call: 例如,要获取字符串'a' ,您可以调用:

myTuple[0][0]

If you wanted to iterate over all the elements in the lists, you could use the chain method form itertools . 如果要迭代列表中的所有元素,可以使用chain方法形式itertools For example: 例如:

from itertools import chain

for i in chain(*myTuple):
    print(i)

You can use reduce , eg. 你可以使用reduce ,例如。 with numpy 与numpy

from functools import reduce
reduce(append, myTuple)

Out[149]: 
array(['a', 'list', 'of', 'strings', 'inside', 'a', 'tuple', 'extra',
       'words', 'for', 'filler'], dtype='<U7')

Or, base 或者,基地

import operator
from functools import reduce
reduce(operator.add, myType, [])
# or, reduce(lambda x, y: x + y, myTuple)

reduce is a classic list operation function along with map , filter , etc. It takes an initial value, here an empty list, and successively applies a function ( append ) to each element of the sequence ( myTuple ). reduce是一个经典的列表操作函数以及mapfilter等。它取一个初始值,这里是一个空列表,并连续地将一个函数( append )应用于序列的每个元素( myTuple )。

Currently you are just iterating through the entire loop and printing out the elements contained within the list. 目前,您只是遍历整个循环并打印出列表中包含的元素。

However, if you want to access a specific element within the list then just refer to it by it's name using .index() 但是,如果要访问列表中的特定元素,则只需使用.index()通过其名称引用它。

Alternatively you can just print(list(indexposition)) 或者你可以打印(列表(索引位置))

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

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