我的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'], [])
可以使用内置函数
zip
将列表拆分为一个简短表达式:请尝试以下代码:
输出:
我们可以通过它的位置访问列表的元素
现在我们也可以使用索引来解包元组
相关问题 更多 >
编程相关推荐