【发布时间】:2021-05-05 17:57:38
【问题描述】:
我有一个包含两个项目的列表。我想遍历这个列表以避免重复非常相似的代码:
for item in ["str1", "str2"]
if <condition>:
var1 = item
else:
var1 = <the "other" item in the list>
#other code that depends on var1 and on item
在第一次迭代中,如果我们最终进入 else 分支,则应为 var1 分配值“str2”,而在第二次迭代中,将为 var1 分配值“str1”。
我能想到解决这个问题的唯一方法是没有循环,即重复我的代码。有没有办法让我保持循环?
EDIT1:添加了循环中的代码具有同时使用 var1 和 item 的语句这一事实。
EDIT2:这是一个不太像我正在尝试做的伪代码示例:
myList = ["str1", "str2"]
outList = []
isSame = True # or False
for item in myList:
val1 = item if isSame else #the other item
str3 = "some text {0} some more text {1}".format(item, val1)
outList.append(str3)
没有循环,这看起来像:
item = "str1"
val1 = "str1" if isSame else "str2"
str3 = "some text {0} some more text {1}".format(item, val1)
outList.append(str3)
item = "str2"
str3 = "some text {0} some more text {1}".format(item, val1)
outList.append(str3)
【问题讨论】:
-
为什么会有循环?只需
if <condition> var1 = mylist[0]; else: var1 = mylist[1]。 -
正如@PranavHosangadi 所说,这个for循环是不必要的,但是如果你仍然想使用for循环,那么在if条件之后添加一个break
-
Pranav 和 ozcanyarimdunya,谢谢你们的 cmets。我意识到我的问题不完整。我的代码的“其余部分”(这是最后一条评论)同时使用了 var1 和列表中的每一项。
-
你可以使用计数器变量
i然后用a[i]和a[-i]读取数组(比如说它叫做a) -
您的列表中可以有两个以上的元素吗?
标签: python list for-loop if-statement