如何在条件中使用列表 [英] How to use lists in conditionals
问题描述
几个小时前,我问了一个问题,但该问题被重复了.我在问我是否可以使用列表索引来验证答案.这是我的原始代码:
I asked a question a couple of hours ago, but it got closed as a duplicate. I was asking if I could use the index of lists to validate answers. This was my original code:
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:keyword_list = ["screen", "cracked", "blank"]
等...
...and keyword_list: keyword_list = ["screen", "cracked", "blank"]
etc....
我被告知(作为对问题的回答):
I got told (as an answer to the question) to do this instead:
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的关键字,则它什么也不会做.
It does not work now: the opening of the text file does not work, it doesn't open, just skips it out, and if you input a keyword with index of more than 0, then it does not do anything.
有人可以告诉我发生了什么事吗?在右目录btw中有一个screen.txt.
Can someone tell me what's happening. There is a screen.txt in the right directory btw.
谢谢:))
推荐答案
您可以执行以下操作:
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
That will work, if your list k
is reasonably small. If your list with keywords is large, then you could do the comparison the other way around by splitting the input message 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
这篇关于如何在条件中使用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!