问题
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)
...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)
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.
Can someone tell me what's happening. There is a screen.txt in the right directory btw.
Thanks :))
回答1:
You could do something like this:
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)
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
来源:https://stackoverflow.com/questions/37413366/how-to-use-lists-in-conditionals