Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

python - Why does this output the first element in the tuple?

I was reading through some answers and this was a solution to printing ['Bill', 'John', 'Tony', 'Phill'] from the list below.

mylist = [('Bill', 1), ('John', 1), ('Tony', 2), ('Phill', 2)]
print([x for x, y in mylist])

What does this line do?

print([x for x, y in mylist])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

x,y in mylist[i]

saves the name of a certain tuple in x and the number in y.


for x,y in mylist

cycles through all the tuples in mylist.


print([x for x,y in mylist])

prints the x of every tuple.


print([y for x,y in mylist])

would print all the numbers.


print([z for z in mylist])

would print all the tuples.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...