【问题标题】:Count items in a lists that have data with a nested structure计算具有嵌套结构数据的列表中的项目
【发布时间】:2021-12-06 00:15:02
【问题描述】:

我的 tsv 文件数据如下所示(模拟样本,真实数据有些不同,而且很大),

Group_one James,jaime,jim,jimmy Robert,Rob,bob Samuel,sam
Group_two Richard,rick,dick Rodney,Rod

因此,数据中的第一级是制表符分隔,数据中的第二级是逗号分隔。我要统计每个单元格中的数据

例如, Group_one 4 3 2 Group_two 2 2

(注意:计算不同版本的名称。

我想如下做,

第 1 步:读取中的每一行 第二步:使用split('\t')解析第一级 第三步:使用split(',')解析二级 第四步:使用len()统计第二批列表,使用end=''

导入系统

def main():

    name_of_table_file = 'file name here'  

    with open(name_of_table_file,'rt') as file_name:
        file_name_lines = file_name.readlines()

    for lines in file_name_lines:
        lines=lines.rstrip()
        lines = lines.rsplit('\t')
        for comma_separated_items in lines:
            comma_separated_items = comma_separated_items.rsplit(',')
            print(len(comma_separated_items),end='\t')
           
main()

我想出了以下代码,

问题是数据被打印为,

Group_one 
Group_two
43232 

代替:

Group_one 4 3 2
Group_two 3 2

(第一级数据中的行没有被维护,我在想 for 会在每行结束后打印到下一行)。

我试图查看是否可以将文件加载到 pandas 数据帧中,使用基于逗号的分隔来计算每个单元格,但在 google,here 上运气不佳。

我该如何解决这个问题?

【问题讨论】:

    标签: python-3.x list


    【解决方案1】:

    当我运行它时,我没有得到你得到的结果,所以我不确定问题中是否缺少某些细节。但是这样的事情应该可以工作:

    with open(name_of_table_file, "rt") as file_name:
        file_name_lines = file_name.readlines()
    
    for line in file_name_lines:
        groups = line.split("\t")
        
        output = groups[0]
        for group in groups[1:]:
            output += f" {len(group.split(','))}"
        print(output)
    

    输出:

    Group_one 4 3 2
    Group_two 3 2
    

    【讨论】:

    • ,我使用了你的代码,奇怪的是我得到了不同的答案。它只打印行中的第一个元素(您的打印语句是否需要嵌套到第二个 for 循环中才能接收 len 值?)。我在 Windows 上,这可能是一个空白问题。我会将修改粘贴到对我有用的代码中。
    【解决方案2】:

    这是对我有用的代码。

    for lines in file_name_lines:
                # lines=lines.rstrip(), I removed the strip and kept the end of line '\n' which I use to jump to newline when needed later down the line.
                lines = lines.rsplit('\t')
                # print(lines)
                for comma_separated_items in lines:
                    comma_separated_items = comma_separated_items.rsplit(',')
                    if comma_separated_items[-1].endswith('\n'):# testing for newline
                        print(len(comma_separated_items))
                    else:
                        print(len(comma_separated_items),end='\t')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2015-04-20
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      相关资源
      最近更新 更多