【问题标题】:turn column of numbers into comma separated list将数字列转换为逗号分隔列表
【发布时间】:2017-06-04 07:26:24
【问题描述】:

您好,我有这样的数据

40
50
70

我想要这样的输出: 40,50,70

我试过了:

from sys import argv
script, pos_file, output = argv
positions = []
with open(pos_file) as f:
   for x in f:
      positions.append(x)
print positions

它给了我一个像'40\n'、'50\n'、'70\n'这样的列表,所以它将数字视为字符串并打印行分隔符\n。如何修改此代码以执行我想要的操作?

谢谢。

【问题讨论】:

    标签: python list csv


    【解决方案1】:

    我已经为自己弄清楚了这一点,因为它可以帮助其他任何人(将我的专栏视为 csv 文件而受到轻微欺骗):

    from sys import argv
    import csv
    script, pos_file, output = argv
    positions = []
    out = open(output, "w")
    
    with open(pos_file, "rb") as csv_file:
         f = csv.reader(csv_file)
         for x in f:
             positions.append(x[0])
         print ",".join(positions)
    
    out.write(",".join(positions))
    

    【讨论】:

    • 'code' from sys import argv script, pos_file, output = argv position = [] with open(pos_file) as f: for x in f: x.rstrip("\n"); position.append(x) intpos = [map(int, x) for x in position] print intpos print pos
    【解决方案2】:

    您本可以使用您的原始代码。您需要添加一行,以删除换行符。

    from sys import argv
    script, pos_file, output = argv
    positions = []
    with open(pos_file) as f:
       for x in f:
          x.rstrip("\n");
          positions.append(x)
    print positions
    

    最后一行打印一个列表。在您的第二个代码中,您创建了一个字符串而不是一个列表。

    【讨论】:

    • 我怎样才能遍历这个 - 例如:for x in position: print x if x
    • @SamLipworth for x in positions: if int(x) < 1000: print x(添加正确的 python 格式)
    猜你喜欢
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 2020-04-07
    • 2018-06-20
    相关资源
    最近更新 更多