【问题标题】:Processing two lists, iterating line by line and join values处理两个列表,逐行迭代和连接值
【发布时间】:2015-02-04 17:27:01
【问题描述】:
w = open("input1.txt", "r")
f = open("input2.txt", "r")
for line1 in w:
    words1 = line1.split()
    for line2 in f:
        words2 = line2.split()
        print (words1[0]+" "+words1[1]+" "+words1[2]+" "+words1[3]+" "+words1[4]+" "+words1[5]+";"+words2[0])

f.close()
w.close()

我在每个文本文件中都有一个列表:input1.txt 和 input2.txt

input1.txt1 2 3

input2.txta b c

我正在尝试加入每个元素与另一个元素配对的列表。 所以,输出应该是:

1a
1b
1c 
2a 
2b 
2c 
3a 
3b 
3c

使用上面的代码,我只能做到:

1a
1b
1c

然后就结束了。

我怎样才能让它选择下一行并做同样的事情?

【问题讨论】:

  • 它停止的原因是文件有一个指向文件中当前位置的指针。当您从文件中读取时,该计数器将移动到文件中的当前位置。当您读取整个文件时,计数器位于末尾,因此不再读取。您可以通过在 for line2 in f: 之前添加 f.seek(0) 来修复当前代码使用 Eithos 的答案,因为它只读取文件一次。

标签: python list loops matrix


【解决方案1】:

在我看来,你真正需要的就是这个:

w = open("input1.txt", "r").read()
f = open("input2.txt", "r").read()

for number in w.split():
    for letter in f.split():
        print number, letter

f.close()
w.close()

只需拆分结果并正常迭代两者。您将获得数字和字母配对,而无需您已经创建的所有额外 (?) 代码。

经过编辑以反映来自 OP 的新信息

按照您的要求,使用readlines(),如下所示:

f = open("input2.txt", "r").read().split()
w = open("input1.txt", "r").readlines()

for timestamp in w:
    for letter in f:
        print timestamp.rstrip(), letter

rstrip 方法将处理使用readlines() 自动传入的newline 字符。

【讨论】:

  • 我想让这个例子简单一些,但我的数据看起来像这样:List 1: 2014 1 1 0 10 0, 2014 1 1 0 20 0, 2014 1 1 0 30 0, 2014 1 1 0 40 0, 2014 1 1 0 50 0List 2: a, b, c, dList 1 是时间戳。使用您的代码,它一次拾取一个块,2014 年,然后是 1,然后是 1,然后是 0
  • @armen 你能在你的 OP 中更新它(并精确地格式化它在文件中出现的格式)吗?
  • @armen 同时,您能否更具体地说明列表 1 中的哪些数字将附加到字母对应项?我们是否跳过2014 1 1,仅将剩余的 3 位数字映射到a, b, c?您在这里包含了一封信 d,所以这让我有些疑问。
  • 感谢您这么快回复。结果应如下所示:2014 1 1 0 10 0 a, 2014 1 1 0 10 0 b, 2014 1 1 0 10 0 c, 2014 1 1 0 10 0 d。然后它应该选择下一个时间戳:2014 1 1 0 20 0 a, 2014 1 1 0 20 0 b, 2014 1 1 0 20 0 c, 2014 1 1 0 20 0 d。然后下一个:2014 1 1 0 30 0 a, 2014 1 1 0 30 0 b, 2014 1 1 0 30 0 c, 2014 1 1 0 30 0 d
  • @armen 谢谢。输入实际上是用逗号分隔的,还是(更有可能)是在没有逗号的单独行中?
【解决方案2】:

你可以试试下面的。

w = open('input1', 'r')
f = open('input2', 'r')
for line1 in w:
    words1 = line1.split()
for line2 in f:
    words2 = line2.split()
for z in words1:
    for y in words2:
        print(z+y)
f.close()
w.close()

输出:

1a
1b
1c
2a
2b
2c
3a
3b
3c

【讨论】:

    【解决方案3】:
    with open("input1.txt", "r") as f1, open("input2.txt", "r") as f2:
        a = f1.readline().split()
        b = f2.readline().split()
    
    for i in a:
        for x in b:
            print "{}{}".format(i,x)
    

    输出:

    1a
    1b
    1c   
    2a
    2b 
    2c
    3a
    3b
    3c
    

    【讨论】:

      【解决方案4】:
      s1="1 2 3"
      s2 = "a b c"
      s1 = s1.split()
      s2 = s2.split()
      for a in s1:
          for b in s2:
              print(a+b)
      1a
      1b
      1c
      2a
      2b
      2c
      3a
      3b
      3c
      

      【讨论】:

        【解决方案5】:
            w = open("input1.txt", "r").read().split()
            f = open("input2.txt", "r").read().split()
            final_list = []
            for number in w:
                final_list += map(lambda:x+number,f)
        
            f.close()
            w.close()
        
           print final_list
           >>> [1a,1b,1c,2a,2b,2c,3a,3b,3c]
        

        【讨论】:

          【解决方案6】:

          假设我们通过考虑有 2 个字符串列表 ab 来简化问题,现在您想在这些列表中创建所有组合,那么您可以简单地使用:

          a = ["1", "2", "3"]
          b = ["a", "b", "c"]
          for i in a:
              for j in b:
                  print i+j
          

          现在的问题是从文本文件中读取列表内容。

          w = open("input1.txt", "r")
          f = open("input2.txt", "r")
          line1 = w.read()
          line2 = f.read()
          for word1 in line1.split():
              for word2 in line2.split():
                  print word1+word2
          
          f.close()
          w.close()
          

          【讨论】:

            【解决方案7】:

            看起来你读的文件很好,所以让我们分配

            f=['a','b','c']
            w=[1,2,3]
            

            那么这样的事情应该可以工作:

            out=[] #blank list
            for num in w:
               for let in f:
                  out.append(str(num)+let)
            

            out 是您发布的所需输出

            【讨论】:

              【解决方案8】:

              你可以使用 itertools 中的 izip,如下所示:-

              import itertools
              w = open("input1.txt", "r")
              f = open("input2.txt", "r")
              
              numbers_list = w.readlines()
              letters_list = f.readlines()
              result = []
              for index, numbers in enumerate(numbers_list):
                  numbers = numbers.strip('\n').split(' ')
                  letters = letters_list[index]
                  letters = letters.strip('\n').split(' ')
                  for letter in letters:
                      paired_tuples= itertools.izip_longest(numbers, '', fillvalue=letter)
                      result += [a+b for a,b in paired_tuples]
              print result
              
              f.close()
              w.close()
              

              同时处理多行。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2022-06-27
                • 2013-07-02
                • 2016-05-14
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多