【问题标题】:Selecting the other item in a 2-item list选择 2 项列表中的其他项
【发布时间】: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 &lt;condition&gt; 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


【解决方案1】:

在编辑之后,这听起来更像是算法而不是 Python 特定的语法。

这是我的看法,适用于两个项目,但可能会扩展到更多:

isSame = True
items = ["str1", "str2"]
len_items = len(items)

for item in items:
    var1 = item 

    if not isSame:
        # Get index of the "next" item or 0 if item is the last:
        next_index = (items.index(item) + 1) % len_items
        var1 = items[next_index]

    # other code that depends on var1 and on item

    print(item, var1)

给予:

str1 str1
str2 str2

如果isSameTrue,并且:

str1 str2
str2 str1

如果isSameFalse

【讨论】:

  • 如果 list.append() 是唯一的语句,则此方法有效。我的道歉,我应该更笼统。我最好说 val2 = #expr 取决于 item, outList.append((val1, val2))
  • 谢谢!这有帮助。 :) 我也想出了自己的解决方案。但我将你的答案标记为答案,因为它看起来更干净。
【解决方案2】:

您可以使用enumerate() 函数同时迭代列表元素的索引。然后,检查您的条件并在newindex 处将项目替换为mylist 的元素。你如何获得newindex?通过将一个添加到index,然后根据列表的长度取余数。这意味着如果您的条件不满足,newindex 将是列表的下一个元素。如果这是列表的最后一个元素,它将环绕到第一个元素。

len(mylist) = 2 的情况下,这样做会给我们列表的other 元素。 本例中的条件是item的最后一个字符必须是"1"

def is_same(x):
    return x[-1] == "1"

mylist = ["str1", "str2"]
newlist = []

for index, item in enumerate(mylist):
    if is_same(item):
        var1 = item
    else:
        newindex = (index + 1) % len(mylist)
        var1 = mylist[newindex]

    # Do other shenanigans with item
    value = item + " hello " + var1
    newlist.append(value)

运行此代码后,newlist 包含两项,第一项仅来自 str1,但第二项来自 str1str2

# newlist: 
['str1 hello str1', 'str2 hello str1']

【讨论】:

    【解决方案3】:

    您似乎在寻找ternary operator

    这是一个语法示例:

    is_nice = True
    state = "nice" if is_nice else "not nice"
    

    在你的情况下,有一个列表:

    my_list = ["str1", "str2"]
    var1 = my_list[0] if <condition> else my_list[1]
    

    【讨论】:

      【解决方案4】:

      看起来很笨重,但是

      myList = ["str1", "str2"]
      for item in myList:
          if <condition>:
              var1 = item
          else:
              var1 = [i for i in myList if i != item][0]
          
          #other code that depends on var1 and on item
      

      【讨论】:

        【解决方案5】:

        如果创建 outList 是您在 for 循环中完成的唯一任务,那么您可以通过执行以下操作来避免 for 循环:

        myList = ["str1", "str2"]
        outList = []
        isSame = True # or False
        outList = list(zip(myList, reversed(myList)) if isSame else zip(myList, myList))
        

        【讨论】:

          【解决方案6】:

          我将 p3j4p5 回复标记为答案,因为它看起来更干净。一直以来,我一直在考虑布尔值,因为理想情况下我需要的是一种分配列表中元素的“非”的方法。我想出了一种方法来编写代码,同时以这种方式思考。在这里发布此评论以供批评。这是一种不好的编码方式吗?

          myList = {True: "str1", False: "str2"}
          outList = []
          isSame = True # or False
          for key in myList:
              item  = myList[key]
              val1 = myList[key] if isSame else myList[not key]
              str3 = "some text {0} some more text {1}".format(item, val1)
              outList.append(str3)
          

          我之所以考虑布尔值,是因为字符串“str1”和“str2”在我的实际代码中表示相反的意思。我认为用布尔值编写代码会使代码在传达我正在尝试做的事情方面具有可读性。

          感谢大家的帮助!

          【讨论】:

            【解决方案7】:

            您可以将它们转换为集合并减去。

            items = ["str1", "str2"]
            for item in items:
                if <condition>:
                    var1 = item
                else:
                    var1 = list(set(items) - {item})[0]
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-08-10
              • 2021-05-27
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-10-17
              相关资源
              最近更新 更多