如何同时使用两个列表?

时间:2020-10-27 16:25:00

标签: python list loops

我有2个清单;材料及其相应的数量。
例如,列表为:words=["banana","apple","orange","bike","car"]numbers=[1,5,2,5,1]
通过这些列表,我如何确定哪个项目数量最少,哪个项目数量最多。
我不知道从哪里开始谢谢!

5 个答案:

答案 0 :(得分:1)

使用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),则可以直接在这些对上使用minmax以获取最小/最大组合:

>>> min(zip(numbers, words))
(1, 'banana')
>>> max(zip(numbers, words))
(5, 'bike')

或者从dict对创建(word, number),并在其上使用minmax。这只会给您单词,但是您可以从字典中获得相应的数字:

>>> 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'

答案 1 :(得分:1)

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
>>> 

答案 2 :(得分:0)

对于这样的事情,您应该使用字典或元组列表:

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

答案 3 :(得分:0)

让事情变得简单:如果您只想要一件最少且一件最多的商品

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])

答案 4 :(得分:0)

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}