如何将列表中的项目附加到另一个列表?

时间:2014-04-07 21:14:53

标签: python list append

我需要打印与最高价格(10.0)匹配的所有商品的名称作为highestPriceList 我的问题是,即使价格与最高价格相匹配,也不会追加。列表是[itemName,price]

inventoryList = [['Steak', ' 10'], ['Milk', ' 2'], ['Fruits', ' 10'], ['Canned Corn', ' 0.50']]
highestPriceItem = 10.0
highestPriceList = []

for item in inventoryList:
    if item[1] == highestPriceItem:
        highestPriceList.append(item[0])
print ("Item with highest wholsesale price: ",highestPriceList)

有什么建议吗?

4 个答案:

答案 0 :(得分:1)

您正在比较字符串,其中' 10'10.0不同。请改用数字:

inventoryList = [['Steak', 10], ['Milk', 2], ['Fruits', 10], ['Canned Corn', 0.50]]
highestPriceItem = 10.0
highestPriceList = []

for item in inventoryList:
    if item[1] == highestPriceItem:
        highestPriceList.append(item[0])
print ("Item with highest wholsesale price: ",highestPriceList)

或者,如果由于某个原因未在问题中显示,您需要保留字符串,那么至少要比较数字:

inventoryList = [['Steak', ' 10'], ['Milk', ' 2'], ['Fruits', ' 10'], ['Canned Corn', ' 0.50']]
highestPriceItem = 10.0
highestPriceList = []

for item in inventoryList:
    if float(item[1]) == highestPriceItem:
        highestPriceList.append(item[0])
print ("Item with highest wholsesale price: ",highestPriceList)

答案 1 :(得分:0)

In [66]: inventoryList = [['Steak', ' 10'], ['Milk', ' 2'], ['Fruits', ' 10'], ['Canned Corn', ' 0.50']]

In [67]: maxPrice = max(float(L[1]) for L in inventoryList)

In [68]: highestPriceList = [L for L in inventoryList if float(L[1]) == maxPrice]

In [69]: highestPriceList
Out[69]: [['Steak', ' 10'], ['Fruits', ' 10']]

答案 2 :(得分:0)

您的价格清单是一个字符串,第一个字符是空格。比较是浮点数10.0结果,循环中的每个if都是false。它应该是

inventoryList = [['Steak', '10.0'], ['Milk', '2.0'], ['Fruits', '10.0'], ['Canned Corn', '0.50']]
highestPriceItem = 10.0
highestPriceList = []

for item in inventoryList:
  if float(item[1]) == highestPriceItem:
    highestPriceList.append(item[0]) # Only the item is appended and not the price
print ("Item with highest wholsesale price: ",highestPriceList)

或者,将价格更改为列表中的浮动。如果您需要进行进一步的操作,那么以后可能会节省时间。

答案 3 :(得分:0)

以下将是一个体面的(给定你的约束)这样做的方式。您inventoryList的结构保持不变,highestPriceItem也可以保持其当前形式。我使用list comprehension代替for statement来提高效率,更重要的是,更具可读性。

inventoryList = [['Steak', ' 10'], ['Milk', ' 2'], ['Fruits', ' 10'], ['Canned Corn', ' 0.50']]
highestPriceItem = 10.0
highestPriceList = [item[0] for item in inventoryList if float(item[1]) == highestPriceItem]

print ("Item with highest wholsesale price: ", highestPriceList)