How to use lists in conditionals

会有一股神秘感。 提交于 2019-12-12 02:12:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!