【问题标题】:How to a split string into different values?如何将字符串拆分为不同的值?
【发布时间】:2014-04-09 09:37:26
【问题描述】:

我有:

file=open("file.txt","r")

文件格式为:

apple\red\3 months
pear\green\4 months

如何将文件拆分为列表形式:

fruit = ['apple', 'pear']
colour = ['red','green']
expire = ['3 months', '4 months']

我完全不知道,希望能得到帮助。我现在拥有的:

file = open('file.txt','r')
for i in file:
   i.readline()
   i.split('\ ')

不知道这是对的,但不知道我什么时候把它分成了:

apple
red
3 months
pear
green
4 months

我如何将第一行和之后的每 3 行变成一个列表,以及之后的第 2 行和每 3 行,依此类推。

【问题讨论】:

    标签: python list file split


    【解决方案1】:

    您可以拆分行并将每个部分添加到列表中。例如:

    fruit = []
    colour = []
    expire = []
    
    file = open('file.txt','r')
    for i in file:
       fruit_, colour_, expire_ = i.split('\\')
       fruit.append(fruit_)
       colour.append(colour_)
       expire.append(expire_)
    

    【讨论】:

    • 您可以简化为fruit_, colour_, expire_ = i.split("\\"),然后使用更有意义的变量名称简化为append,尽管如果行不符合预期,这会引发错误。
    • @jonrsharpe 是的。完毕。谢谢!
    • 如果 OP 想在每一行添加更多的东西,这不是很可扩展。
    • @Scorpion_God 这是真的;在 Python 3.x 中,它可能是 fruit_, colour_, expire_, *_ = i.split("\\")
    • @jonrsharpe 我的意思是如果 OP 也想存储该数据。如果您阅读我的解决方案,我想您会明白我的意思。
    【解决方案2】:

    你可以这样做:

    s = ['apple\red\3 months', 'pear\green\4 months']
    
    fruit = [i[0] for i.split('\\') in s]
    colour = [i[1] for i.split('\\') in s]
    expire = [i[2] for i.split('\\') in s]
    

    【讨论】:

      【解决方案3】:

      您可以通过.split() 方法使用序列解包,然后将每个值添加到其单独的列表中。请注意,反斜杠用于转义特殊序列,因此您必须使用反斜杠转义反斜杠并改为在 '\\' 上拆分。

      >>> line = 'apple\red\3 months'
      >>> line = line.split('\\')
      >>> line
      ['apple', 'red', '3 months']
      >>> fruit, colour, expire = line
      >>> print(fruit, colour, expire)
      apple red 3 months
      

      从文件中读取时,您还必须.strip() 每行,因为它们末尾有换行符。解决方案:

      data = {'fruits': [], 'colours': [], 'expires': []}
      
      with open('file.txt') as f:
          for line in f:
              fruit, colour, expire = line.strip().split('\\')
              data['fruits'].append(fruit)
              data['colours'].append(colour)
              data['expires'].append(expire)
      

      可扩展版本:

      columns = ['fruits', 'colours', 'expires']
      data = {c: [] for c in columns}
      
      with open('file.txt') as f:
          for line in f:
              line = line.strip().split('\\')
              for i, c in enumerate(columns):
                  data[c].append(line[i])
      

      未经测试的单线:

      with open('file.txt') as f: data = {c: d for c, *d in zip(*(['fruits', 'colours', 'expires']+[line.strip().split('\\') for line in f]))}
      

      【讨论】:

        【解决方案4】:
        for l in open("i.txt"):
            for m in l.split('\\'):
                print(m.strip())
        

        【讨论】:

          【解决方案5】:

          zip* 一起使用:

          >>> s = r'''apple\red\3 months
          pear\green\4 months'''
          >>> zip(*(x.rstrip().split('\\') for x in s.splitlines()))
          [('apple', 'pear'), ('red', 'green'), ('3 months', '4 months')]
          

          对于文件,您可以执行以下操作:

          with open("file.txt") as f:
              fruit, colour, expire = zip(*(line.rstrip().split('\\') for line in f))
          

          zip 返回元组而不是列表,因此您可以使用 list() 将它们转换为列表。

          【讨论】:

            【解决方案6】:

            你走对了。

            fruit = []
            color = []
            expire = []
            file = open('file.txt','r')
            for i in file:
                   i.readline()
                   f, c, exp = i.split('\\')
                   fruit.append(f)
                   color.append(c)
                   expire.append(exp)
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2017-08-11
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-01-07
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多