【问题标题】:How to use lists in conditionals如何在条件句中使用列表
【发布时间】:2016-09-21 15:42:54
【问题描述】:

几个小时前我问了一个问题,但它被关闭为重复。我在问是否可以使用列表索引来验证答案。这是我的原始代码:

message = input("Problem: ")
for item in keyword_list:
    if item in message:
        if item == "screen" or item == "cracked" or item == "blank":
            subp.call("screen.txt", shell=True)

...和关键字列表:keyword_list = ["screen", "cracked", "blank"] 等...

我被告知(作为问题的答案)改为这样做:

message = input("Problem: ")
for item in keyword_list:
    if item in message:
        if item in keyword_list[:3]:
            subp.call("screen.txt", shell=True)

现在不行了:文本文件的打开不行,打不开,直接跳过,如果你输入了一个索引大于0的关键字,那么它什么也不做。

谁能告诉我发生了什么。顺便说一句,正确的目录中有一个screen.txt。

谢谢:))

【问题讨论】:

  • “但它被关闭为重复”如果这是同一个问题,人们将再次关闭它。这是一个不同的问题吗?
  • 向我们展示您的完整脚本,keyword_list 中有多少索引?
  • 这不是同一个问题,这是我听从他们的建议时遇到的错误
  • 如果无法打开文件,显示打开文件的代码。另外我不确定subp.call("screen.txt") 应该做什么? screen.txt 是一个可执行文件吗?
  • 有12个索引。我现在无法访问代码,因为我正在上课,抱歉。

标签: python list file python-3.x python-3.4


【解决方案1】:

你可以这样做:

import subprocess as subp

k = ['screen','cracked','blank']
m = input('Problem:')
for i in k:
    if i in m:
        file = r'C:\somedir\somefile.txt'
        subp.Popen (file, shell=True) 

如果您的列表 k 相当小,这将起作用。如果您的关键字列表很大,那么您可以通过拆分输入消息m 来进行相反的比较

import subprocess as subp

k = ['screen','cracked','blank']
m = input('Problem:')
for i in m.split():
    if i in k:
        file = r'C:\somedir\somefile.txt'
        subp.Popen (file, shell=True)  

HTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 2021-02-22
    • 2012-06-04
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    相关资源
    最近更新 更多