【问题标题】:picking and writing out some fractions of list with for-loop用for循环挑选和写出列表的一些部分
【发布时间】:2019-01-07 12:44:26
【问题描述】:

有一个 csv-file 形式的数据集,其中包含一些数据表格。
我想挑出具有相同数字的分数。
例如我有一个列表

a = [1,1,2,2,3,3,4,4,4,5,5,5,5,6]

我想要一个循环,它用相同的数字写入text-files
file_1.txt 包含1,1
file_2.txt 包含2,2
file_3.txt 包含3,3
file_4.txt 包含4,4,4
file_5.txt 包含5,5,5,5
file_6.txt 包含6

我仍然没有真正的结果,因为到目前为止一切都错了。

【问题讨论】:

  • 即使您的结果是错误的并且似乎不起作用,也请与我们分享您的尝试。
  • 您是否希望输出重复相同的次数 n 次?还是您只想获取每个元素的计数?
  • @Felk:如果您查看a,此处所需的输出似乎很清楚。重点是他/她的尝试
  • 查看itertools.groupby

标签: python loops csv for-loop writefile


【解决方案1】:

更简洁的方法是使用itertools.groupbystr.join

from itertools import groupby

for num, group in groupby(a):
    filename = "file_%d.txt"%num
    with open(filename, 'w') as f:
        f.write(",".join(map(str, group)) + "\n")

另一个重要的一点是你should always use the with statement when reading and writing to files


使用groupby 假定数据已经排序。另一种方法是使用collections.Counter:

from collections import Counter

for num, count in Counter(a).items():
    filename = "file_%d.txt"%num
    with open(filename, 'w') as f:
        f.write(",".join([str(num)]*count) + "\n")

【讨论】:

    【解决方案2】:

    如果我理解正确,这应该可以:

    for x in set(a):
        text_file = open("file_"+str(x)+".txt", "w")
        text_file.write(((str(x)+',')*a.count(x))[:-1])
        text_file.close()
    

    第三行中的[:-1] 是删除多余的逗号;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2017-04-19
      • 2022-01-06
      相关资源
      最近更新 更多