如何将拆分字符串转换为不同的值?

时间:2014-04-09 09:37:26

标签: python list file split

我有:

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行和第3行写入列表,然后是第2行和第3行,依此类推。

7 个答案:

答案 0 :(得分:3)

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

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_)

答案 1 :(得分:1)

您可以按照以下方式执行此操作:

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]

答案 2 :(得分:1)

您可以使用.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]))}

答案 3 :(得分:0)

for l in open("i.txt"):
    for m in l.split('\\'):
        print(m.strip())

答案 4 :(得分:0)

你是对的。

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)

答案 5 :(得分:0)

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 :(得分:0)

fruit, color, expire = [], [], []
for i in open('file.txt'):
        fr,col,exp = i.split('\\')
        fruit.append(fr)
        color.append(col)
        expire.append(exp)
print fruit  #['apple', 'pear']
print color  #['red', 'green']
print expire #['red', 'green']