【问题标题】:Using variables inside an if statement in python [duplicate]在python的if语句中使用变量[重复]
【发布时间】:2020-04-16 09:58:09
【问题描述】:

如何在 python 的 if 语句中使用变量?例如,month_report 包含:

October
November
December
January

cycle_report 包含:

October,Monthly
November,Monthly
November,Quarterly
January,Monthly

以下是我认为可以使用变量的方式。

mcount = 0
qcount = 0
ncount = 0

for month in month_report:
    for x in cycle_report:
        if x == "{month},Monthly":
            mcount += 1
        elif x == "{month},Quarterly":
            qcount += 1
        else:
            ncount += 1

【问题讨论】:

  • cycle_report 是地图吗?如果是这样,那么它将是cycle_report[month],因为值将被报告。如果完整的"{month},Monthly" 是关键,那么您必须在检查之前对其进行格式化。
  • f"{month},Monthly" ?
  • 对不起,我是 python 的新手。我该如何使用它? f"{month},Monthly"?

标签: python


【解决方案1】:

我不确定您的数据结构,但考虑到它们是字符串列表:

In [1]: month_report = ['October', 'November']

In [2]: cycle_report = ['October, monthly', 'November, monthly']

In [3]: for month in month_report:
   ...:     for cycle in cycle_report:
   ...:         if month + ', monthly' == cycle:
   ...:             print('yes')
   ...:
yes
yes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-05
    • 2018-07-06
    • 2017-10-25
    • 2020-10-07
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多