Timeline for Iterating through file multiple times (Python)
Current License: CC BY-SA 3.0
11 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
May 7, 2015 at 6:27 | comment | added | chw21 | Are you sure this gives the right output? Wouldn't it change the location of the 8 and 5? | |
May 7, 2015 at 6:12 | history | edited | Steven Rumbalski | CC BY-SA 3.0 |
Updated answer to include comments.
|
May 7, 2015 at 6:12 | vote | accept | Anastasia | ||
May 7, 2015 at 6:08 | comment | added | Steven Rumbalski |
@Anastasia: Add one line at the top of the for-loop: line = line.strip() , otherwise the newline is preserved on the names that do not have underscores.
|
|
May 7, 2015 at 6:04 | comment | added | Anastasia | if I use results = collections.OrderedDict() and change the rest of the code, the code prints out var1, 1, var2, 2, var3, 3, var1 4 6, var2 5 8, var3 7 9 (new line instead of commas) | |
May 7, 2015 at 5:58 | comment | added | Steven Rumbalski |
@Anastasia: No need to sort the result. collections.OrderedDict preserves the insertion order of keys.
|
|
May 7, 2015 at 5:57 | comment | added | Steven Rumbalski |
No need to guard key = key.split('_')[0] with if '_' in key: because "nounderscore" == "nounderscore".split('_')[0] .
|
|
May 7, 2015 at 5:56 | comment | added | Anastasia | Also, the names of variables are words, they don't end with a number, so I can't simply re-order the file based on the numerical value. | |
May 7, 2015 at 5:55 | comment | added | Steven Rumbalski |
@Anastasia: Then make results be an OrderedDict . Change results[key].append(value) to results.setdefault(key, []).append(value) .
|
|
May 7, 2015 at 5:48 | comment | added | Anastasia | I clarified my question. I need to preserve the order of input file, so the output file has to be in order var1, var2,var3 | |
May 7, 2015 at 5:41 | history | answered | Burhan Khalid | CC BY-SA 3.0 |