【问题标题】:Simple way to "mix" respectively two lists in python?在python中分别“混合”两个列表的简单方法?
【发布时间】:2012-11-04 20:42:53
【问题描述】:

我有以下问题:

我需要在 python 中分别“混合”两个列表...

我有这个:

names = open('contactos.txt')
numbers = open('numeros.txt')
names1 = []
numbers1= []
for line in numbers:
    numberdata = line.strip()
    numbers1.append(numberdata)
print numbers1

for line in names:  
    data = line.strip()
    names1.append(data)
print names1

names.close()
numbers.close()

这首先打印 300 个数字,然后打印相应的 300 个名称,我需要做的是创建一个新文件 (txt),在一行中打印名称和数字,用逗号 (,) 分隔,像这样:

Name1,64673635
Name2,63513635
Name3,67867635
Name4,12312635
Name5,78679635
Name6,63457635
Name7,68568635
..... and so on...

我希望你能帮助我做到这一点,我已经尝试过使用“for”,但如果我一次迭代两个列表,我不确定该怎么做,谢谢 :)

【问题讨论】:

  • 必须是python吗?还是 bash 解决方案也可以满足您的需要?
  • 附带说明,在访问文件时,最好使用上下文管理器:with open(filename) as file: \ # process file 其中“\”代表换行符。此构造可确保您的文件始终关闭,无论任何异常行为如何。

标签: python file list


【解决方案1】:

一次性完成:

import itertools

with open('contactos.txt') as names, open('numeros.txt') as numbers:
    for num, name in itertools.izip(numbers, names):
        print '%s, %s' % (num.strip(), name.strip())

这会并行读取两个文件,而不是一次将每个文件完全读取到内存中。

【讨论】:

    【解决方案2】:

    以这种方式混合两个列表的“pythonic”方式是zip 函数!

    names = open('contactos.txt')
    numbers = open('numeros.txt')
    names1 = []
    numbers1= []
    for line in numbers:
        numberdata = line.strip()
        numbers1.append(numberdata)
    
    for line in names:  
        data = line.strip()
        names1.append(data)
    
    names.close()
    numbers.close()
    
    for name, number in zip(names1, numbers1):
        print '%s, %s' % (name number)
    

    还有其他更好的方法来打印格式化文本(例如 Yuushi 的回答)。我也喜欢使用with 语句和列表推导,例如

    with open('contactos.txt') as f:
        names = [line.strip() for line in f]
    
    with open('numeros.txt') as f:
        numbers = [line.strip() for line in f]
    
    for name, number in zip(names, numbers):
        print '%s, %s' % (name, number)
    

    最后,我只想评论一下如果没有 zip 功能如何做到这一点。如果有不同数量的数字和名称,我不确定您要做什么,但是您可以使用像这样的for 循环作为最后一位,以在单个 for 循环中访问两个列表中的值:

    for i in range(len(numbers)):
        print '%s, %s' % (names[i], numbers[i])
    

    如果名称多于数字,则此代码尤其会引发异常,因此您可能需要添加一些代码来处理它。

    【讨论】:

      【解决方案3】:

      zip 会将两个列表组合在一起,让您将它们写入文件:

      In [1]: l1 = ['one', 'two', 'three']
      
      In [2]: l2 = [1, 2, 3]
      
      In [3]: zip(l1, l2)
      Out[3]: [('one', 1), ('two', 2), ('three', 3)]
      

      但是,您可以为自己节省一点时间。在您的代码中,您分别迭代每个文件,从每个文件创建一个列表。您也可以同时遍历两者,一次创建您的列表:

      results = []
      with open('contactos.txt') as c:
          with open('numeros.txt') as n:
             for line in c:
                results.append([line.strip(), n.readline().strip()])
      
      
      print results
      

      这使用with 语句(上下文管理器),它基本上为您处理文件的关闭。这将遍历contactos,从numeros 中读取一行并将该对附加到列表中。您甚至可以删除列表步骤并在同一循环中直接写入第三个文件:

      with open('output.txt', 'w') as output:
          with open('contactos.txt', 'r') as c:
              with open('numeros.txt', 'r') as n:
                  for line in c:
                      output.write('{0}, {1}\n'.format(line.strip(), n.readline().strip()))
      

      【讨论】:

        【解决方案4】:

        利用zip:

        for num, name in zip(numbers, names):
            print('{0}, {1}'.format(num, name))
        

        【讨论】:

        • 或者也可以使用itertools.izip,这样您就不会一次读取整个文件(除非您使用的是 Python 3,在这种情况下您编写的内容很好)
        • 您的解决方案是正确的,除了给定的参数应该是“numbers1”和“names1”,因为这些是列表名称,我修复了它,现在它可以工作了,谢谢!
        猜你喜欢
        • 2014-01-30
        • 2019-04-27
        • 1970-01-01
        • 2017-12-26
        • 2011-04-12
        • 2015-04-29
        • 2019-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多