【问题标题】:having 2 list how to switch between them based on the same index number of elements? [closed]有 2 个列表如何根据元素的相同索引数在它们之间切换? [关闭]
【发布时间】:2021-12-18 11:39:24
【问题描述】:

如何在包含我需要在具有相同索引号的元素之间切换的项目的 2 个列表之间切换?

示例:

l1=["foo","bar"," "]
l2 = ["dog","cat","house "]

预期输出:

l1=["dog","cat","house"]

直到现在我都被困在这里:

 if "nan" in l1:
   index_nan = l1.index("nan") # this return 2

如何从这里继续???

【问题讨论】:

  • 您只想要l1 中的l2 的项目吗??
  • 你的问题不清楚。看来l1 = l2 可以解决您的问题。
  • 我想用 l2 的项目替换 l1 的项目
  • "我想用 l2 的项目替换 l1 的项目" 好的。您知道如何更改列表中的项目吗?对于l1 中的每个项目,您知道如何决定替换的内容吗?你知道如何重复一个过程吗?或者:你知道列表切片是什么吗?或者:为什么不完全忽略l1 并继续使用l2?或者:您真的需要更换这些物品吗?为什么?将l1 用作同一个l2 列表的另一个名称是否可行?

标签: python list replace


【解决方案1】:

试试这个:

l1=["foo","bar"," "]
l2 = ["dog","cat","house "]
temp = l1.copy()
l1=l2
l2=temp

输出:

>>> l2
['foo', 'bar', ' ']
>>> temp
['foo', 'bar', ' ']
>>> l1
['dog', 'cat', 'house ']

【讨论】:

    【解决方案2】:

    您可以交换变量以在 2 个列表之间切换值

    >> l1=["foo","bar"," "]
    >> l2 = ["dog","cat","house "]
    >> l1,l2 = l2,l1
    

    它会在元素上切换对应的索引值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-06
      • 2019-08-11
      • 1970-01-01
      • 2023-03-31
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      相关资源
      最近更新 更多