簡體   English   中英

索引在2D列表中的位置,以從同一列表中獲取子返回值

[英]Index Position in a 2D list to get a sub return value from same list

所以基本上我已經制作了兩個不同的列表,並且它們的位置彼此相應。 用戶輸入項目名稱。 程序在預定義列表中搜索其索引,然后從第二個列表中提供其各自的值。

我想要的是第一個評論(2d列表)上的列表。 是否有可能使用該列表,用戶輸入:'面包'。

程序得到它的索引,然后返回值5.基本上在2d列表索引。我搜索了很多,但沒有用。

如果您能提供代碼或至少以正確的方式指導我。

謝謝。

#super_market_prices=[['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]
'''
Program listing Super Market Prices
Search by name and get the price
'''
super_market_items=['Bread','Loaf','Meat_Chicken','Meat_Cow']
super_market_prices=[5,4,20,40]

item=str(input('Enter item name: '))
Final_item=item.capitalize()                    #Even if the user inputs lower_case
                                                #the program Capitalizes first letter
try:
    Place=super_market_items.index(Final_item)
    print(super_market_prices[Place])
except ValueError:
    print('Item not in list.')

你不想要2D列表,你想要一本字典,幸運的是,從2D列表(每個子列表只有兩個元素)到字典是非常簡單的:

prices = [['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]
d = dict(prices)
# {'Bread': 5, 'Loaf': 100, 'Meat_Chicken': 2.4, 'Meat_Cow': 450}

現在你所要做的就是查詢字典(O(1)lookup):

>>> d['Bread']
5

如果要啟用錯誤檢查:

>>> d.get('Bread', 'Item not found')
5
>>> d.get('Toast', 'Item not found')
'Item not found'

您可以使用zip輕松地從這兩個單獨的序列中的“二維列表”中zip

super_market_prices=[['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]

l1, l2 = zip(*super_market_prices)

>>> print(l1)
('Bread', 'Loaf', 'Meat_Chicken', 'Meat_Cow')
>>> print(l2)
(5, 100, 2.4, 450)

並保持你的代碼不變。

這是解決您問題的另一項工作。 PS:我使用@ user3483203的建議來使用item.title()而不是item.capitalize()因為后者導致帶有下划線的字符串出錯。 在這里,我正在利用每個項目的價格成功的事實。 因此index+1

super_market_prices=np.array([['Bread',5],['Loaf',100],['Meat_Chicken',2.4],['Meat_Cow',450]]).ravel()

item=str(input('Enter item name: '))
Final_item=item.title()      

try:
    index = np.where(super_market_prices == Final_item)[0] 
    print (float(super_market_prices[index+1][0]))
except ValueError:
    print('Item not in list.')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM