Reputation: 1255
I have a code like below,
from io import StringIO
a = """ab: 01dvfgf
cd: 01fgvr windows
ab: 02hjuy linux
cd: 01erttt windows
lm: 02hjkkk"""
s = StringIO(a)
a_01 = []
a_02 =[]
zone = ['01', '02']
for elements in zone:
for line in s:
if line[4:6] == '01':
a_01.append(line)
elif line[4:6] == '02':
a_02.append(line)
print('a_01', *a_01, sep = "\n")
print('a_02', *a_02, sep = "\n")
In this code can I replace below 4 lines into two so that I don't have to write it again and again for different zones
if line[4:6] == '01':
a_01.append(line)
elif line[4:6] == '02':
a_02.append(line)
something like:
if line[4:6] == elements:
"a_" + elements.append(line)
Upvotes: 1
Views: 60
Reputation: 7353
Use a dict
to store the values.
from io import StringIO
a = """ab: 01dvfgf
cd: 01fgvr windows
ab: 02hjuy linux
cd: 01erttt windows
lm: 02hjkkk"""
s = StringIO(a)
zone_dict = {'01': list(), '02': list()}
for line in s:
#print(line)
for key in zone_dict.keys():
#print(key)
if line[4:6] == key:
zone_dict[key].append(line)
zone_dict
Output:
{'01': ['ab: 01dvfgf\n', 'cd: 01fgvr windows\n', 'cd: 01erttt windows\n'],
'02': ['ab: 02hjuy linux\n', 'lm: 02hjkkk']}
Upvotes: 0
Reputation: 15738
from collections import defaultdict
...
s = StringIO(a)
zones = defaultdict(list)
for line in s:
zones[line[4:6]].append(line)
for zone, lines in zones.items(): # can be iterated just as a regular dict
print(zone, *lines, sep="\n")
Upvotes: 3