将元组拆分为列表而不将其拆分为单个字符

2024-09-27 07:28:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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'], []) 

Tags: thein列表artistsort元组innerprint
3条回答

可以使用内置函数zip将列表拆分为一个简短表达式:

def sort_artists(x):
    return tuple(zip(*x))

artists = [("The Beatles", 270.8), ("Elvis Presley", 211.5), ("Michael Jackson", 183.9)]

names, earnings = sort_artists(artists)
print(names)
print(earnings)

请尝试以下代码:

def sort_artists(x):
    artist = []
    earnings = []
    z = (artist, earnings)
    for inner in x:
        artist.append(inner[0])
        earnings.append(inner[1])
    return z

artists = [("The Beatles", 270.8), ("Elvis Presley", 211.5), ("Michael Jackson", 183.9)]
print(sort_artists(artists))

输出:

(['The Beatles', 'Elvis Presley', 'Michael Jackson'], [270.8, 211.5, 183.9])
def sort_artists(x):
    artist = []
    earnings = [] 
    for i in range(len(x)):
        artist.append(x[i][0])
        earnings.append(x[i][1])
    return (artist,earnings)

我们可以通过它的位置访问列表的元素

print(artist[0]) 
#o/p
('The Beatles', 270.8)

现在我们也可以使用索引来解包元组

#for artist
print(artist[0][0])
o/p
'The Beatles'

#for earnings
print(artist[0][1])
o/p
270.8

相关问题 更多 >

    热门问题