这破坏了我的大脑,我到处搜寻都无济于事。这是一个例子:
masNoun = ["Mann", "Junge"]
femNoun = ["Frau"]
neuNoun = ["Madchen", "Kind"]
masArt = ["ein"]
femArt = ["eine"]
firstProSing = ["Ich"]
seconProSing = ["du"]
thirdProSing = ["Er", "Sie"]
firstVerb = ["bin"]
seconVerb = ["bist"]
thirdVerb = ["ist"]
subject = firstProSing or seconProSing or thirdProSing
verb = firstVerb or seconVerb or thirdVerb
object1 = masArt or femArt
object2 = masNoun or femNoun
输出:输出似乎总是第一个变量。我尝试使用随机模块如下:
object1 = random.choice(masNoun or femNoun)
结果仍然相同,第一个变量是输出选项。 “或”函数似乎对我的例子不起作用。我很难过。任何帮助将不胜感激!
答案 0 :(得分:2)
Python中的or
关键字用作布尔运算符 - 如果操作数是布尔值,它将表达式计算为True
或False
。
在这种情况下,操作数不是布尔值,因此or
运算符将返回评估为True
的操作数。请记住,or
运算符以short-circuit方式运行。
例如:
>>> a = 2
>>> b = 3
>>> a or b
2
>>> b or a
3
对我来说,看起来你希望变量从给定的可能值列表中取一个随机值。
在这种情况下,你想要的是这些:
import random
subjects = ['Ich', 'du', 'er', 'sie']
subject = random.choice(subjects)
编辑:根据评论,要使用多个变量列表而不是一个组合列表执行此操作,您可以执行以下操作:
import random
firstProSing = ["Ich"]
secondProSing = ["du"]
thirdProSing = ["Er", "Sie"]
subject = random.choice(firstProSing + secondProSing + thirdProSing)
+
运算符将采用列表并将它们组合在一起,因此此代码相当于:
subjects = firstProSing + secondProSing + thirdProSing
# Comment: Here the content of subjects is ['Ich', 'du', 'Er', 'Sie']
subject = random.choice(subjects)
答案 1 :(得分:0)
'或'声明不是这样的。这是一个布尔值,而不是随机选择。随机选择可以这样做:
import random
subjects = ["Ich", "du", "Er", "Sie"]
verbs = ["bin", "bist", "ist"]
objects1 = ["ein","eine"]
objects2 = ["Mann", "Junge","Frau"]
subject = random.choice(subjects)
verb = random.choice(verbs)
object1 = random.choice(objects1)
object2 = random.choice(objects2)
答案 2 :(得分:0)
in OR clause if leftmost condition is True python will not look further
firstProSing = ["Ich"]
seconProSing = ["du"]
thirdProSing = ["Er", "Sie"]
subject = firstProSing or seconProSing or thirdProSing
print(firstProSing)
['Ich']
# here the first value is empty or False, python looks
# right and finds that seconProSing is True so its value 'du' is chosen
subject = "" or seconProSing or thirdProSing
print(subject)
['du']