Reputation: 1
What I am trying to do is split the elements within a list by the ";" and add it to a new list. My current code is:
n = []
s = open("rankings.txt").readlines()
for i in s:
n[i] = s[i].split(';')[1]
Each element in s containts ";", so it should be able to split each one there. This is the contents of s.
['Team 1;12\n', 'Team 2;45\n', 'Team 3;66\n', 'Team 4;77\n', 'Team 5;8\n', 'Team 6;99\n', 'Team 7;22\n', 'Team 8;13\n', 'Team 9;46\n', 'Team 10;97\n', 'Team 11;64\n', 'Team 12;65\n', 'Team 13;32\n', 'Team 14;98\n', 'Team 15;78\n', 'Team 16;752\n', 'Team 17;72\n', 'Team 18;73\n', 'Team 19;76\n', 'Team 20;419\n', 'Team 21;48\n', 'Team 22;16\n', 'Team 23;469\n', 'Team 24;82\n', '\n']
I want n to contain [12, 45, 66...]
Upvotes: 0
Views: 60
Reputation: 430
below solution should work and list1 is your input list.
num_list = []
for ele in list1:
ele = ele.rstrip("\n")
if ele:
num_list.append(ele.split(";")[1])
print (num_list)
Upvotes: 0
Reputation: 11
The following code should do what you're expecting. Instead of readlines()
, just use open()
and run a loop, which achieves the same task, only efficiently.
new_list = []
f = open("rankings.txt", "r")
for x in f:
temp = x.split(";")
new_list.append(int(temp[1]))
Edited after comment to typecast to int
Upvotes: 1
Reputation: 588
There are several issues here:
for i in s
means i
is a string from the list, not an index. Change to for i in range(len(s))
to get integers.
n
is an empty list, and does not have an n[i]
for any non-negative i
. Append new members by changing to n.append(...)
.
There are members in s
without ;
(the last one). Maybe add an if statement?
Or you could write this in a nice little comprehension:
n = [int(x.split(';')[1]) for x in s if ';' in x]
Upvotes: 0
Reputation: 1055
You can do this with a list comprehension. This works on your case, you might need to modify it a bit depending on specific cases that happen to break it, if you have some input with mismatches, but it shouldn't be very difficult:
n = [int(x.split(';')[1]) for x in s if ';' in x]
where s
is your list of strings.
Note that the if at the end is because your last item is only '\n'
and the int ignores the '\n'
part. These are the parts you might need to modify in different cases.
If you want me to expand what the list comprehension is/does write so in the comment.
Upvotes: 0