如何使两个列表相互对应?

问题描述 投票:1回答:3

我在这里有2个列表:

list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]

我想让数字分配给情感? (快乐等于2,悲伤等于5,依此类推)。理想情况下,我想这样做,以便您可以比较list1中的项目,例如:

if happy > sad:
    print ("you are happy")

我想使这段代码尽可能高效,所以我不想为list1的每个变量分别分配一个数字。

预先感谢。

python list
3个回答
1
投票

您可以一起zip列表并从中创建一个dict

list1 = ["happy", "sad", "grumpy", "mad"]
list2 = [2, 5, 6, 9]

moods = dict(zip(list1, list2))
# This will create a dictionary like this
# {'happy': 2, 'sad': 5, 'grumpy': 6, 'mad': 9}


if moods["happy"] > moods["sad"]:
    print("You are happy")
else:
    print("You are sad")

输出为:

You are sad

0
投票

最好的方法是创建这样的字典:

d ['happy'] = 2 ...然后比较值

if d['happy'] < d['sad'] :
emotion = 'sad'

0
投票

您可以在python中使用字典。表示键值对的一种简单方法。how to use dictionary

© www.soinside.com 2019 - 2024. All rights reserved.