如何将其转换为python列表理解
因此,基本上,我正在尝试制作一个列表理解函数,如果输入是一个字符,并且是选项列表中的一个选项[a,b,c,d,e,a,b,c,d,e],它将添加到一个名为answers的列表中如何将其转换为python列表理解,python,python-3.x,list,input,list-comprehension,Python,Python 3.x,List,Input,List Comprehension,因此,基本上,我正在尝试制作一个列表理解函数,如果输入是一个字符,并且是选项列表中的一个选项[a,b,c,d,e,a,b,c,d,e],它将添加到一个名为answers的列表中 def anwser(numQ): anwserlist = list() choice = [a, b, c, d, e, A, B, C, D, E] for num in numQ: a = input(prompt) if len(a) > 1 and
def anwser(numQ):
anwserlist = list()
choice = [a, b, c, d, e, A, B, C, D, E]
for num in numQ:
a = input(prompt)
if len(a) > 1 and a in choice:
awnserlist.append(a)
这是我目前所拥有的,但它不起作用
anwsers = [a = input(f'What is the anwser to question{num}?')for num in range(1,numQ+1) if len(a) < 2 and in choices]
anwsers=[a=input(f'What'anwser to question{num}'),如果len(a)<2且在选项中,则范围(1,numQ+1)中的num
您可以使用以下命令
answerList = [a for num, a in zip(numQ, iter(lambda: input(prompt), None)) if len(a) > 1 and a in choice]
但我不推荐。并非每个循环都需要或应该被列表理解所取代,您现在拥有的一切都很好。首先,我建议将您的UI与检查逻辑分开(我不确定此应用程序是/做什么的)。其次,
answer
打破了封装,并以未显示的字母varsa
、b
、c
等访问全局范围。这些名称不好,从函数内部访问它们是不安全的——如果它们在调用之间意外更改,可能会引入难以发现的bug。最后,请提供一个可运行的代码和程序规范的解释。谢谢。如果你只是忽略了一个无效的输入,你怎么知道哪些答案对应于哪些问题?如果答案无效,我建议至少在列表中添加None
。另一个选项是读取输入,直到提供有效答案。
valid_choices = {'a', 'b', 'c','d','e','A', 'B','C','D','E'}
numQ = 3
answers = [a for a in (input(f'What is the anwser to question{num}? ') for num in range(1, numQ+1)) if a in valid_choices]
print(answers)