我有一个包含两列的数据文件,我想将其放入一个列中。
从现在起我已经拆分了列 以 open("test.txt") 作为 input_data:
for line in input_data: # This keeps reading the file
li=line.strip()
#print repr(line) #Each line is being returned as a string
column = line.split()
# print column
nb1=column[0]
nb2=column[1]
我该如何继续?
最佳答案
您可以使用Python's slicing notation与列上的 +
运算符结合使用。例如,连接列表的前两个元素是通过以下方式完成的:
=>>> l=["a","b","c","d"]
>>> a=[l[0]+l[1]]+l[2:]
>>> a
['ab', 'c', 'd']
a=[l[0]+l[1]]+l[2:]
连接 (+
) 前两个元素 ([l [0]+l[1]]
)以及剩余的列(l[2:]
)。
在您的代码中,它可能是:
columns = [column[0]+ column[1]]+ column[2:]
关于python - 将两列合并为一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15064668/