【问题标题】:Python: Putting two diffrent entries from one array togetherPython:将一个数组中的两个不同条目放在一起
【发布时间】:2018-12-27 18:28:30
【问题描述】:

我遇到了一些非常简单的事情(可能):

我有一个列表,其中列表条目 [0] 应与列表条目 [1] 合并,[2] 应与 [3] 合并,依此类推。

最后,在配对合并后,我想将结果保存在一个新列表中。 到目前为止我创建的 for 循环从未工作过,那么也许有人可以帮助我吗?

非常感谢!

像这样:

list1 = ["A1", "A2", "B1", "B2", "C1", "C2"]
list2 = []

# The Output for list2 should be like: ["A1A2", "B1B2", "C1C2"]

【问题讨论】:

  • 欢迎在 Stackoverflow 上发帖!您能否编写代码尝试部分解决方案,即使它不能完全工作。 How to create a Minimal, Complete, and Verifiable example
  • 看看range函数和join方法。
  • list2 = [x+y for x,y in zip(list1[::2], list1[1::2])] 有关解释,请自行查看文档并搜索列表切片、zip 和列表理解。
  • 非常感谢您的帮助! :)

标签: python arrays python-3.x list merge


【解决方案1】:

我们可以使用range 函数来获取偶数索引。

list2 = []

for i in range(0, len(list1), 2):
    value = list1[i] + list1[i + 1]
    list2.append(value)

【讨论】:

  • 列表理解更简洁:list2 = [list1[i]+list1[i+1] for i in range(0,len(list1),2)]
  • 非常感谢Oleksandr,你帮了我很多!现在可以了 :) 祝你有美好的一天!
【解决方案2】:

列表理解解决方案 -

[list1[i]+list1[i+1] for i in range(0, len(list1), 2)]

如果你有以上列表理解,join 就在不远处 -

["".join(x[i: i+2]) for i in range(0, len(x), 2)]

【讨论】:

    【解决方案3】:
    **Solution**
    list1 = ["A1", "A2", "B1", "B2", "C1", "C2","D1"]
    list2 = []
    index_1 = 1
    
    for item in list1:
    #    print(item)
        if index_1 % 2:
            list2.append(item)
        else:
            list2[len(list2) - 1] = list2[len(list2) - 1] + item
        index_1 = index_1 + 1
    
    
     print(list2)
    

    【讨论】:

      猜你喜欢
      • 2016-11-29
      • 2020-07-09
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多