同一行中多个循环的顺序

时间:2015-12-27 12:08:16

标签: python python-2.7 python-3.x

(2:red, 10:white) > (3:blue, 7:green)
.................
................

我有一个这种类型的文件。我需要在它旁边获得每种颜色的价值。我试过这个

for line in file.splitlines():
a, b = line.split(">")
a_value = [one[0] for one in sec for sec in item.split(':') in sec for sec in a.split(',')]

但是我在循环中存在多个问题,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

重复颜色

文件内容:

file = """(2:red, 10:white) > (3:blue, 7:green)
(12:red, 110:white) > (13:blue, 17"""
带有defaultdict

list在此处运作良好:

from collections import defaultdict

colors = defaultdict(list)

for line in file.splitlines():
    for col in line.split('>'):
        for entry in col.strip()[1:-1].split(','):
            num, name = entry.split(':')
            colors[name].append(int(num))

结果是每种颜色的值列表:

>>> colors
defaultdict(list,
            {'blue': [3, 13],
             'green': [7, 17],
             'red': [2, 12],
             'white': [10, 110]})

非重复颜色

假设所有颜色都是唯一的,您可以这样做:

colors = {}
for line in file.splitlines():
    for col in line.split('>'):
        for entry in col.strip()[1:-1].split(','):
            num, name = entry.split(':')
            colors[name] = int(num)

>>> colors
{'blue': 3, 'green': 7, 'red': 2, 'white': 10}

答案 1 :(得分:1)

因为你有重复的键你不能使用字典理解,你可以使用private async void ThreadMethod_ListenClient() { while (true) { if (ClientQueue.Count == 0) continue; Client client = (Client)ClientQueue.Dequeue (); if (client.Reader != null) { string Say = await client.Reader.ReadLineAsync(); if (Say != null) { if (Say.Length != 0) { Console.WriteLine (Say); } } } ClientQueue.Enqueue (client); } } 存储列表中的所有颜色值,颜色为键:

defaultdict

输入:

from collections import defaultdict
d = defaultdict(list)

with open("in.txt") as f:
    for line in map(str.rstrip,f):
        for s in line.split(" > "):
            for sub in s[1:-1].split(", ", 1):
                v, k = sub.split(":", 1)
                d[k].append(v)

输出:

(2:red, 10:white) > (3:blue, 7:green)
(12:red, 19:white) > (22:blue, 22:green)
(34:red, 14:white) > (19:blue, 13:green)

如果你想输出元组,你只需要迭代这些项目:

defaultdict(<type 'list'>, {'blue': ['3', '22', '19'], 'white': ['10', '19', '14'], 'green': ['7', '22', '13'], 'red': ['2', '12', '34']})

输出:

for k, v in d.items():
    for val in v:
        print((k, val))

如果你想使用正则表达式:

('blue', '3')
('blue', '22')
('blue', '19')
('white', '10')
('white', '19')
('white', '14')
('green', '7')
('green', '22')
('green', '13')
('red', '2')
('red', '12')
('red', '34')

输出将是相同的:

from collections import defaultdict
import re

d = defaultdict(list)

with open("in.txt") as f:
    r = re.compile("\d+:\w+")
    for line in map(str.rstrip, f):
        for s in r.findall(line):
            v, k = s.split(":", 1)
            d[k].append(v)