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

Python 将元组拆分为列表,而不将其拆分为单个字符,python,string,list,tuples,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 a

我的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
这就是目前正在发生的情况(没有收入部分):

请尝试以下代码:

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

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

def排序(x):
返回元组(zip(*x))
艺术家=[(《披头士》,270.8)、(《猫王》,211.5)、(《迈克尔·杰克逊》,183.9)]
姓名、收入=艺术家排序(艺术家)
打印(姓名)
印刷品(收入)
我们可以通过它的位置来访问列表中的元素

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

谢谢。
+=
是不是用错了?是不是只针对单个字符?@william3031使用
+=
尝试连接列表。例如,
[1,2]+[3,4]=[1,2,3,4]
…你遇到的问题是字符串可以被视为字符列表,这就是为什么你要单独获得它们
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