identical123456 identical123456 - 3 months ago 19
Python Question

Alternative way to using for loop

Suppose a file looks like this:

abcd 1
abcd 2
abcd 3
xyz 1
xyz 2


My code:

if "abcd" in line:
do something

elif "xyz" in line:
do something


If both "abcd" and "xyz" dynamically change, how would I capture them by writing the same loop?

Edit:

Can I write a universal loop which counts the number of elements in abcd and xyz? without taking abcd and xyz in its condition.

BPL BPL
Answer

Not sure I've understood correctly your question, but here's a possible way to gather key & values from your file:

import re
from collections import defaultdict

file = """


abcd      1
abcd       2
abcd        3
xyz        1
xyz       2




"""

output = defaultdict(list)

for line in file.split("\n"):
    if line.strip() == "":
        continue

    key, value = re.search(r'(.*?)\s+(.*)', line).groups()
    output[key].append(value)

print(output)

for k, v in output.iteritems():
    print("{0} has {1} items".format(k, len(v)))
Comments