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')
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:
myTuple[0][0]
If you wanted to iterate over all the elements in the lists, you could use the chain
method form itertools
. For example:
from itertools import chain
for i in chain(*myTuple):
print(i)
You can use reduce
, eg. with 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
).
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()
Alternatively you can just print(list(indexposition))
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.