[英]Splitting a tuple in to a list without splitting it in to individual characters
我的 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
將列表拆分為一個簡短的表達式:
def sort_artists(x):
return tuple(list(t) for t in zip(*x))
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 = []
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
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.