Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将包含多个项目的列表转换为单个项目行_Python_List - Fatal编程技术网

在python中将包含多个项目的列表转换为单个项目行

在python中将包含多个项目的列表转换为单个项目行,python,list,Python,List,我想从以下内容转换文本文件中的行: animal cat, mouse, dog, horse numbers 22,45,124,87 为此: animal cat animal mouse animal dog animal horse numbers 22 numbers 45 numbers 124 numbers 87 如何在python中进行此转换 谢谢使用collections.defa

我想从以下内容转换文本文件中的行:

animal    cat, mouse, dog, horse  
numbers    22,45,124,87
为此:

animal    cat  
animal    mouse  
animal    dog  
animal    horse  
numbers    22  
numbers    45  
numbers    124  
numbers    87
如何在python中进行此转换


谢谢

使用
collections.defaultdict


您可能希望搜索类似的问题

使用
collections.defaultdict

with open('thefile.txt') as fin:
  with open('result.txt') as fou:
    for line in fin:
      key, values = line.split(None, 1)
      vs = [x.strip() for x in values.split(',')]
      for v in vs:
          fou.write('%s    %s\n' % (key, v))

您可能希望搜索类似的问题

使用zip,您可以执行以下操作:

with open('thefile.txt') as fin:
  with open('result.txt') as fou:
    for line in fin:
      key, values = line.split(None, 1)
      vs = [x.strip() for x in values.split(',')]
      for v in vs:
          fou.write('%s    %s\n' % (key, v))
inp="""animal    cat, mouse, dog, horse  
numbers    22,45,124,87
"""
for line in inp.splitlines():
    key,data = line.split(None,1)
    print '\n'.join("%s%8s" % line
                    for line in zip([key.strip()] * (data.count(',')+1),
                                    (item.strip() for item in data.split(','))))

使用zip,您可以执行以下操作:

inp="""animal    cat, mouse, dog, horse  
numbers    22,45,124,87
"""
for line in inp.splitlines():
    key,data = line.split(None,1)
    print '\n'.join("%s%8s" % line
                    for line in zip([key.strip()] * (data.count(',')+1),
                                    (item.strip() for item in data.split(','))))