con*_*eie 4 python list python-3.x
我这里有 2 个列表:
list1 = [happy, sad, grumpy, mad]
list2 = [2, 5, 6, 9]
Run Code Online (Sandbox Code Playgroud)
我想让数字分配给情绪?(happy 等于 2,sad 等于 5,以此类推)。理想情况下,我想这样做,以便您可以比较 list1 中的项目,例如:
if happy > sad:
print ("you are happy")
Run Code Online (Sandbox Code Playgroud)
我想让这段代码尽可能高效,所以我不想分别为 list1 中的每个变量分配一个数字。
您可以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")
Run Code Online (Sandbox Code Playgroud)
输出是:
You are sad
Run Code Online (Sandbox Code Playgroud)
编辑:
如果您不关心其他值是什么(受Laurent B. 的回答启发),另一种选择是直接选择一种心情:
list1 = ["happy", "sad", "grumpy", "mad"]
list2 = [2, 5, 6, 9]
mood = list1[list2.index(max(list2))]
print("You are", mood)
Run Code Online (Sandbox Code Playgroud)
输出:
You are mad
Run Code Online (Sandbox Code Playgroud)