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

时间:2019-06-23 12:40:50

标签: python string list tuples

我的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]”,这将给我“披头士乐队”,但是当我尝试将其附加到空白列表时,它将其分成单独的字母。怎么了?

错误(尽管我也尝试过一点“收益”,以及使用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'], []) 

4 个答案:

答案 0 :(得分:2)

尝试此代码:

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])

答案 1 :(得分:1)

您可以使用内置函数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)

答案 2 :(得分:1)

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

答案 3 :(得分:0)

    df.insert(0, 'new_column', [data,,,])

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

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)