[英]How to convert a list of 2-tuples to a list of their first elements
我有一個這樣的清單-
[(1, 3),(2, 2)]
我喜歡把它轉換成——
[1,2]
我正在做的是——
c = [(1, 3),(2, 2)]
output = []
for a,b in c:
output.append(a)
return output
有沒有辦法在 1 行中做到這一點?
您可以使用list-comprehension
output = [a for a,_ in c]
這里的_
對應於問題中使用的b
,是虛擬變量的常規名稱。
使用列表理解並從每個元組中獲取第一個元素:
c = [(1, 3),(2, 2)]
print([i[0] for i in c])
OUTPUT:
[1, 2]
另一種方法是:
[x[0] for x in c]
使用 zip() function。
b = [*list(zip(*a))[0]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.