【发布时间】:2019-06-23 12:40:50
【问题描述】:
我的 Python 代码有问题。我想从元组中获取值并将它们放入列表中。在下面的示例中,我想让艺术家进入一个列表,而收入进入另一个列表。然后将它们放入一个元组中。
def sort_artists(x):
artist = []
earnings = []
z = (artist, earnings)
for inner in x:
artist += inner[0]
earnings += inner[1]
return z
artists = [("The Beatles", 270.8), ("Elvis Presley", 211.5), ("Michael Jackson", 183.9)]
print(sort_artists(artists))
我可以打印 `inner[0] ,这会给我 'The Beatles',但是当我尝试将它附加到空列表时,它会将其拆分为单个字母。怎么了?
错误(尽管我也尝试过没有“收益”位,以及使用append 和其他东西:
Traceback (most recent call last):
File "Artists.py", line 43, in <module>
print(sort_artists(artists))
File "Artists.py", line 31, in sort_artists
earnings += inner[1]
TypeError: 'float' object is not iterable
Command exited with non-zero status 1
想要的输出:
(['Elvis Presley', 'Michael Jackson', 'The Beatles'], [270.8, 211.5, 183.9])
这是目前正在发生的事情(没有收入位):
(['T', 'h', 'e', ' ', 'B', 'e', 'a', 't', 'l', 'e', 's', 'E', 'l', 'v', 'i', 's', ' ', 'P', 'r', 'e', 's', 'l', 'e', 'y', 'M', 'i', 'c', 'h', 'a', 'e', 'l', ' ', 'J', 'a', 'c', 'k', 's', 'o', 'n'], [])
【问题讨论】:
-
“出了什么问题?” 在您的上下文中,
+是序列的串联,因此[]是一个序列,@987654328 @ 是一个字符串,它是一个字符序列,所以你有[]+['a','b']的等价物(在解释器中尝试)。您必须使用列表的.append(object)方法,它不会解包它的参数,而只是将它插入到列表的末尾。