繁体   English   中英

我将如何 go 关于实现多个输入 - 在 if 语句中 - 在 Python 中使用列表理解

[英]How would I go about achieving multiple inputs - within if statements - with list comprehension in Python

我最近开始学习列表理解,发现它非常有用。 但是,我刚刚遇到了这样一个事实,即我显然无法将 if 语句与输入链接起来——不确定它的语法是什么。 例如,我之前编写的这个字典附加代码可以正常工作(其中 if else 子句只是让它在第一个输入通过时将 \n 添加到语句中:

key = list(
str(input(f"Please enter a Key for value {x + 1}: "))
if x == 0
else str(input(f"\nPlease enter a Key for value {x + 1}: "))
for x in range(3))

但是,在向 append 编写代码时,通过理解将日期写入列表时,我了解到我不能只写:

date = list(str(input('Please enter the year: ')) 
        if x == 0 str(input('Please enter the year: ')) 
        elif x == 1 else str(input('Please enter the day: ')) 
        for x in range(3))

所以我只是想知道如何写:

date = []

for i in range(3):
if i == 0:
    date.append(str(input("Please enter the year: ")))
elif i == 1:
    date.append(str(input("\nPlease enter the month: ")))
else:
    date.append(str(input("\nPlease enter the day: ")))

使用列表理解。

这里有两种方法。 在我看来,循环更好,因为它更具可读性。 我毫不怀疑其他人会不同意,但无论如何:

date = []

for t in ['year', 'month', 'day']:
    v = input(f'Please enter the {t}:')
    date.append(v)

print(date)

date = [input(f'Please enter the {t}:') for t in ['year', 'month', 'day']]

print(date)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM