【问题标题】:Joining two list in one array in python在python中的一个数组中加入两个列表
【发布时间】:2016-11-11 15:59:49
【问题描述】:

我想将一个 excel 文件的列连接到另一个 excel 文件的其他 4 列。

代码如下:

Array1 = []
Arraytest1 = []
Arraytest2 = []
with open('file.txt', 'r') as f:
    for line in f:
    List1 = line.split('\t')[:4]
    List2 = line.split('\t')[10]
    Arraytest1.append(List1)
    Arraytest2.append(List2)
    Arraytest1.extend(Arraytest2)
    print 'Array 1   :', Arraytest1

我在输出中看到的是:

数组 1:[['A','B','C','D'],['E']]

数组1:[['A','B','C','D'],'E',['X1','X1','X1','X1'],'E' , Y1]

但我是什么样的:

数组 1:['A','B','C','D','E']

数组1:['X1','X1','X1','X1','Y1']

数组1:['X2','X2','X2','X2','Y2']

等等.. 我会感谢你的帮助

【问题讨论】:

    标签: python arrays excel list arraylist


    【解决方案1】:
    List1 = line.split('\t')[:4]
    

    已经使List1 成为一个列表。

    Arraytest1.append(List1)
    

    正在将该列表放入 ArrayTest1,想想ArrayTest1 = [[List1's contents]]

    然后,当您扩展它时,您将它展平一次,但有一个嵌套列表,这就是您看到结果的原因。

    试试:

    List1 = line.split('\t')[:4]
    List2 = line.split('\t')[10]
    Arraytest1.extend(List1)
    Arraytest2.extend(List2)
    Arraytest1.extend(Arraytest2)
    print 'Array 1   :', Arraytest1 
    

    或者您可以将其替换为:

    Arraytest1 += List1
    Arraytest2 += List2
    

    我确定你知道,但是 append 将对象添加到列表中,extend 将每个对象添加到可迭代对象中。

    追加:

    x = [1,2,3]
    x.append([4,5])
    #x is now [1,2,3,[4,5]]
    

    扩展

    x = [1,2,3]
    x.append([4,5])
    #x is now [1,2,3,4,5]
    x.append(1) #throws error 
    

    Split 返回一个列表...但有时如果您只想拆分一个字符串,只需将其强制转换即可。

    x = "hello"
    x = x.split()
    #x is now ['hello']
    
    x = "hello"
    x = list(x)
    #x is now ['h', 'e', 'l', 'l', 'o']
    

    拆分句子是拆分通常所做的,Python 中的字符串是可迭代的,因此您可以将它们转换为列表以将它们拆分为每个字符。我想这就是你想要的'

    已编辑:根据您的 cmets,这是一个 for 循环问题:

    随着 for 循环的进行,您将添加到列表中,但似乎每次循环时您都想要一个新列表。您不会用干净的列表替换列表,而只是每次都附加到它。尝试替换:

    Arraytest1.extend(List1)
    Arraytest2.extend(List2)
    

    也是:

    Arraytest1 = List1[:]
    Arraytest2 = List2[:]
    

    【讨论】:

    • 谢谢,但是每当我在输出中将'E' 替换为'Test' 而不是'Test' 时,我都会看到类似'T ''E ''S ''T ' 之类的东西
    • 正在编辑我的答案以包括抱歉忘记了 xD 看看
    • A , B ,C, D 和 E 在我的真实代码中是名称,我使用 split 因为我是从 txt 文件中读取它们。此 txt 文件由不同的列组成,由制表符分隔
    • @Braian 我想我发现了你的问题,请参阅已编辑的问题
    • 它工作得很好,只是保持'Test'作为新列的元素,分隔如'T ''E ''S ''T '
    猜你喜欢
    • 2014-02-07
    • 2020-11-13
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 2013-03-25
    • 2011-12-18
    • 1970-01-01
    • 2016-01-27
    相关资源
    最近更新 更多