python - 将两列合并为一列

标签 python

我有一个包含两列的数据文件,我想将其放入一个列中。

从现在起我已经拆分了列 以 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/

相关文章:

python - 如何查找列表中所有出现的多个元素?

python - 防止 subprocess.Popen 在 python 中显示输出

python - 使用 Eclipse/Python 自定义突出显示?

python - 使用 urllib 下载 pdf?

python - 找不到标准 Python 'venv' 模块

python - 如何使用Python在本地服务器上进行基本的CRUD?

python - Jupyter notebook - 抑制 tsfresh 的输出

python - 制作字典的内存效率更高的方法?

python - 大量属性的单独数据存储查询顺序

python - 在不区分大小写的字符串 find 之前和之后插入