[英]Tuple indexing and printing
Python beginner here and a little confused with tuples when working with them as lists. Python初学者在这里,将元组作为列表使用时有点与元组混淆。 I have the code below and to my understanding the peek function should return the first tuple pair but in reality it returns only the first word of that pair.
我有下面的代码,据我所知,偷看功能应返回第一个元组对,但实际上,它仅返回该对的第一个单词。 Why is this??
为什么是这样??
Thanks in advance everyone. 预先感谢大家。
tuples = [('big', 'apple'), ('small', 'orange'), ('medium', 'berry')]
def peek(word_list):
if word_list:
word = word_list[0]
return word[0]
else:
return None
peek(tuples) #prints big
print tuples[0] #prints ('big', 'apple')
word = word_list[0] # first tuple
print word[0] # first entry of the first tuple
You've got two [0]
dereferences. 您有两个
[0]
取消引用。 This code is equivalent to 此代码等效于
print word_list[0][0] # first entry of the first tuple
Get rid of one of them. 摆脱其中之一。
word = word_list[0] # first tuple
print word # first tuple
Try this out and see: 试试看,看看:
word_list = [('big', 'apple'), ('small', 'orange'), ('medium', 'berry')]
word = word_list[0]
print(word)
print(word[0])
In peek function, replace 在窥视功能中,替换
print word[0]
with 与
print word
Since word[0] is actually word_list[0][0] which is 1st element in 1st tuple, ie "big". 由于word [0]实际上是word_list [0] [0],它是第一个元组中的第一个元素,即“大”。 In short, think of "tuples" as a 2*3 array.
简而言之,将“元组”视为2 * 3数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.