l=[(5, 6), 7, 8, 9]
What should I do if I want to take a value of 6 from the list?
printl [0:1]
Then it would be [(5,6)]
, and
l.index(6)
means ValueError:6 is not in list
What should I do if I slice it from the list?
python
l[0]
is a tuple called (5,6)
, so you can look at the second one.
printl[0][1]
# ->6
Or (although this usage may limit the desired situation), they will give you a random disclosure of the types of tuples and lists (sequence unpacking).
(x,y), *rest=l
printy
# ->6
l[0:1]
is a Python slice statement and cannot retrieve any value.l[0][1]
is just a simple l=[(5, 6), 7, 8, 9]
.
If you want to get elements of arbitrary depth from a data structure that mixes lists, tuples, and dictionaries, you don't need to do anything else.
For example, if you want to extract elements from a nest in a list l
with l[b][c]...[x]
, but you don't know the number of indexes idxlist=[a,b,c,...,x]
, you can use the for
statement like this
l=[(5, 6), 7, 8, 9]
idxlist=[0,1]
found_element=l
for index in idxlist:
found_element=found_element [index]
print found_element#6
Alternatively, you can create it like this with the reduce
function.
printreduce(lambdaobj,key:obj[key],
idxlist,
l)l)
© 2024 OneMinuteCode. All rights reserved.