5 回答

TA貢獻1863條經驗 獲得超2個贊
from operator import itemgetter
words = ["banana", "apple", "orange", "bike", "car"]
numbers = [1, 5, 2, 5, 1]
min_item = min(zip(words, numbers), key=itemgetter(1))
max_item = max(zip(words, numbers), key=itemgetter(1))
print("The min item was {} with a count of {}".format(*min_item))
print("The max item was {} with a count of {}".format(*max_item))
輸出:
The min item was banana with a count of 1
The max item was apple with a count of 5
>>>

TA貢獻1820條經驗 獲得超2個贊
用于zip匹配相應的單詞和數字:
>>> words = ["banana", "apple", "orange", "bike", "car"]
>>> numbers = [1, 5, 2, 5, 1]
>>> list(zip(words, numbers))
[('banana', 1), ('apple', 5), ('orange', 2), ('bike', 5), ('car', 1)]
如果將zip它們(number, word)配對,則可以直接在這些對上使用min和max來獲得最小/最大組合:
>>> min(zip(numbers, words))
(1, 'banana')
>>> max(zip(numbers, words))
(5, 'bike')
dict或者從對中創建一個(word, number)并在其上使用min和max。這只會給你單詞,但你可以從字典中獲取相應的數字:
>>> d = dict(zip(words, numbers))
>>> d
{'apple': 5, 'banana': 1, 'bike': 5, 'car': 1, 'orange': 2}
>>> min(d, key=d.get)
'banana'
>>> max(d, key=d.get)
'apple'

TA貢獻1796條經驗 獲得超10個贊
保持簡單:如果您只想要一件最少和一件最多的物品
words=["banana","apple","orange","bike","car"]
numbers=[1,5,2,5,1]
# get least and most amounts using max and min
least_amount = min(numbers)
most_amount=max(numbers)
# get fruit with least amount using index
index_of_least_amount = numbers.index(least_amount)
index_of_most_amount = numbers.index(most_amount)
# fruit with least amount
print(words[index_of_least_amount])
# fruit with most amount
print(words[index_of_most_amount])

TA貢獻1806條經驗 獲得超8個贊
您應該使用字典或元組列表來執行以下操作:
words=["banana","apple","orange","bike","car"]
numbers=[1,5,2,5,1]
dicti = {}
for i in range(len(words)):
dicti[words[i]] = numbers[i]
print(dicti["banana"]) #1
結果字典
{'banana': 1, 'apple': 5, 'orange': 2, 'bike': 5, 'car': 1}
這是如何使用元組列表獲取其中的最大值和最小值的方法
words=["banana","apple","orange","bike","car"]
numbers=[1,5,2,5,1]
numMax = max(numbers)
numMin = min(numbers)
print([x for x,y in zip(words, numbers) if y == numMax ]) #maxes
print([x for x,y in zip(words, numbers) if y == numMin ]) #mins

TA貢獻1784條經驗 獲得超8個贊
words = ["banana","apple","orange","bike","car"]
numbers = [1, 5, 2, 5, 1]
# Make a dict, is easier
adict = {k:v for k,v in zip(words, numbers)}
# Get maximums and minimums
min_value = min(adict.values())
max_value = max(adict.values())
# Here are the results, both material and values. You have also those which are tied
min_materials = {k,v for k,v in adict if v == min_value}
max_materials = {k,v for k,v in adict if v == max_value}
添加回答
舉報