Python if 在语句细节中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13961689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:02:16  来源:igfitidea点击:

Python if in Statement Specifics

pythonif-statementpadding

提问by aescript

In short i have a list of items. lets say they have a name of Object1, Object2,....Object10,....Object20 And so on.

简而言之,我有一个项目清单。假设它们的名称为 Object1、Object2、....Object10、....Object20 等等。

This list depending on use input changes starting points, for the example lets say the list packs in the names of all objects from Object18 up to Object28

此列表根据使用输入更改起点,例如,假设列表包含从 Object18 到 Object28 的所有对象的名称

Im using a statement to select these items from the stored list that goes:

我使用语句从存储的列表中选择这些项目:

for i in nuke.allNodes():
if i.name() in hiddenLists:
    i.setSelected(True)
else:
    i.setSelected(False)

Which works generally... trouble is because "in" (for inside the list) doesnt specify i want it to have to match an entire entry of the list, Instead of JUST selecting Object 18-28 it selects Object1 Object2 And Object 18-28 (reason being of course, Object18 and so on begin with Object1, and the 20s with a 2)

这通常有效......麻烦是因为“in”(对于列表内部)没有指定我希望它必须匹配列表的整个条目,而不是仅选择对象 18-28 它选择对象 1 对象 2 和对象 18- 28(原因当然是 Object18 等以 Object1 开头,而 20 以 2 开头)

I cant pad the strings due to the fact that these are set names a program creates and have to stay the same. my only question is, is there a better operator than in that makes it have to match exactly rather than see Object1 within 'Object18'?

由于这些是程序创建的集合名称并且必须保持不变,因此我无法填充字符串。我唯一的问题是,是否有更好的运算符使它必须完全匹配而不是在“Object18”中看到 Object1?

采纳答案by tom

Looks like hiddenLists is a string (str) entered by the user. Use the splitmethod on that string to make it a list first. Then the "in" clause will do what you want.

看起来 hiddenLists 是用户输入的字符串(str)。首先使用该split字符串上的方法使其成为列表。然后“in”子句将执行您想要的操作。

For instance, if the user enters a comma-separated list:

例如,如果用户输入一个逗号分隔的列表:

hiddenLists = [x.strip() for x in hiddenLists.split(",")]
if i.name() in hiddenLists:
    ...