拆分Python中的列表

时间:2015-11-02 11:03:11

标签: python list function

有一个代码:

def readData():
   file = open('data.txt', 'r')
   listing = []
   for line in file:
      print(line.split())
      depart = line.split()
      m = [line.strip()]
      listing.append(m)

   file.close()
   return listing

def display():
    depart = readData()
    poorest = []
    if int(depart[1]) <= int(depart[2])+int(depart[3]):
        poorest.append(depart[0])
    print(poorest)

&#39;离开&#39;输出将产生这个:

 [['Ladies  250 184 196'], ['Gentlemen  167 321 459'], ['Toys \t180 150 210'], ['Beauty\t450 280 320'], ['Technology\t169 320 279'], ['Home\t120 58 45'], ['Appliances\t210 130 67'], ['Food\t180 45 89'], ['Shoes\t260 100 210'], ['Children 179 50 80']]

但我需要制作这样的东西:

  ['Ladies',  '250', '184,  '196']

每一个。我该如何更改第二个功能?

2 个答案:

答案 0 :(得分:1)

或更多pythonic

def ReadData():
    file = open('data.txt', 'r')
    listing = [[part.strip() for part in line.split()] for line in file]
    file.close()
    return listing

了解List Comprehensions

接下来,我们需要将str转换为int

[[part.strip() if idx == 0 else int(part.strip())
  for idx, part in enumerate(line.split())]
 for line in file]

现在我们有列表:

[['Ladies', 250, 184, 196], ['Gentlemen', 167, 321, 459], ...

答案 1 :(得分:0)

您没有将拆分列表附加到您最终返回的列表中,因此如果您更改以下行

depart = line.split()
m = [line.strip()]
listing.append(m)

listing.append(line.strip().split())

你会得到你想要的东西。