[英]looping through the items of a list in Python
一個簡單的問題,我試圖遍歷這個列表的每個元素,列表本身形成為一個列表列表..
Price = [500, 300, 100, 200]
list_of_pairs = [[1, 1], [2, 2], [1, 1], [2, 2]]
p_11 = []
p_22 = []
p_33 = []
for i in list_of_pairs:
if i[0] == 1 and i[1] == 1:
p_11.append(Price[list_of_pairs.index(i)])
elif i[0] == 2 and i[1] == 2:
p_22.append(Price[list_of_pairs.index(i)])
elif i[0] == 3 and i[1] == 3:
p_33.append(Price[list_of_pairs.index(i)])
print(list_of_pairs)
print(p_11)
print(p_22)
問題是當我遍歷列表並嘗試通過它的第一個和第二個值對每個元素(子列表)進行分類時,它看起來像這樣:
#the output:
[[1, 1], [2, 2], [1, 1], [2, 2]]
[500, 500]
[300, 300]
#what I expected(wanted) for the output:
[[1, 1], [2, 2], [1, 1], [2, 2]]
[500, 100]
[300, 200]
您可以使用enumerate
而不是list_of_pairs.index
來獲取當前元素的索引:
for j, i in enumerate(list_of_pairs):
if i[0] == 1 and i[1] == 1:
p_11.append(Price[j])
elif i[0] == 2 and i[1] == 2:
p_22.append(Price[j])
elif i[0] == 3 and i[1] == 3:
p_33.append(Price[j])
然而,這並不是一個很好的解決方案,也許做同樣事情的更好方法可能是這樣的:
price = [500, 300, 100, 200]
list_of_pairs = [(1, 1), (2, 2), (1, 1), (2, 2)]
# Dictionary that stores the prices for all pairs
p = {}
# Iterate over all prices and pairs at the same time
for price, pair in zip(price, list_of_pairs):
if pair not in p:
p[pair] = [price]
else:
p[pair].append(price)
print(p[(1,1)]) # [500, 100]
print(p[(2,2)]) # [300, 200]
嘗試使用enumerate
直接獲取索引,它更容易、更快:
Price = [500, 300, 100, 200]
list_of_pairs = [[1, 1], [2, 2], [1, 1], [2, 2]]
p_11 = []
p_22 = []
p_33 = []
for index,i in enumerate(list_of_pairs):
if i[0] == 1 and i[1] == 1:
p_11.append(Price[index])
elif i[0] == 2 and i[1] == 2:
p_22.append(Price[index])
elif i[0] == 3 and i[1] == 3:
p_33.append(Price[index])
print(list_of_pairs)
print(p_11)
print(p_22)
因為index
返回list
一個匹配的值的索引,因為你有重復,你得到錯誤的值,使用enumerate
獲取索引:
Price = [500, 300, 100, 200]
list_of_pairs = [[1, 1], [2, 2], [1, 1], [2, 2]]
p_11 = []
p_22 = []
p_33 = []
for i, (a,b) in enumerate(list_of_pairs):
if a == 1 and b == 1:
p_11.append(Price[i])
elif a == 2 and b == 2:
p_22.append(Price[i])
elif a == 3 and b == 3:
p_33.append(Price[i])
print(list_of_pairs)
>>> [[1, 1], [2, 2], [1, 1], [2, 2]]
print(p_11)
>>> [500, 100]
print(p_22)
>>> [300, 200]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.