【问题标题】:Python: Iterating over two lists and replacing elements in one list1 with the element from list2Python:迭代两个列表并将一个列表1中的元素替换为列表2中的元素
【发布时间】:2013-01-21 22:56:10
【问题描述】:

我有两个字符串列表。在包含大约 1000 个字符串元素的 list1 中,您有一个名为“Date”的字符串,它随机出现,紧随其后的是一个包含特定日期的字符串:“17/09/2011”。这种情况发生了大约 70 次。在 List2 中:我有大约 80 个日期,作为字符串。

问题: 我想编写一个同时遍历两个列表的脚本,并按顺序将 list1 中的日期替换为 list2 中的日期。因此,显然您将用 list2 的前 70 个日期替换 list1 中出现的 70 个日期。之后我想将修改后的 list1 写入 .txt 文件。

我试过这个,但我完全卡住了。我是 Python 的超级菜鸟。

def pairwise(lst):
    """ yield item i and item i+1 in lst. e.g.
        (lst[0], lst[1]), (lst[1], lst[2]), ..., (lst[-1], None)
    """
    if not lst: return
    #yield None, lst[0]
    for i in range(len(lst)-1):
        yield lst[i], lst[i+1]
    yield lst[-1], None

for line in file:
      list1.append(line.strip())
for i,j in pairwise(list1):
     for k in list2:
     if i == "Date":
         list1."replace"(j) # Dont know what to do. And i know this double for looping is wrong also.

【问题讨论】:

  • zip(lst,lst[1:]) 应该这样做。
  • 提示:最好的方法是构建一个新列表,而不是修改旧列表。

标签: python list loops


【解决方案1】:

可能是这样的(如果没有没有以下日期的“日期”字符串):

iter2 = iter (list2)
for idx in (idx for idx, s in enumerate (list1) if s == 'Date'):
    list1 [idx + 1] = next (iter2)

with open ('out.txt', 'w') as f:
    f.write ('{}'.format (list1) )

@user1998510,这里稍微解释一下:

enumerate 将列表作为参数并生成形式为(i,列表的第 i 个元素)的元组。在我的生成器(即(x for y in z if a) 部分)中,我将此元组的部分分配给局部变量 idx 和 s。生成器本身只产生索引,因为列表的实际项目(对s)并不重要,因为在生成器本身中我们过滤了有趣的项目if s == 'Date'。在for 循环中,我遍历这个生成器,将其产生的值分配给idx(这是另一个idx,而不是内部idx,因为python 中的生成器不再泄漏它们的局部变量)。生成器生成元素为“日期”的列表的所有索引,for 对其进行迭代。因此,我将第二个列表中的下一个日期分配给所有有趣索引的旧列表的 idx+1st 项。

【讨论】:

  • 在循环中使用list2iter = iter(list2),而不是idx2 计数器,然后使用list1[idx1 + 1] = next(list2iter)
  • 感谢您的 Hyper。你能告诉我我需要学习哪些功能来理解你的代码吗?迭代和枚举我猜?
猜你喜欢
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 2019-04-28
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-20
相关资源
最近更新 更多