+ 2
How to split an element in a list? - Python 3
If I had a list that looked like: list1 = [âA dog, a catâ, âa mouse, a rabbitâ] How would I iterate through the list so I could split it using .split(â,â) I would want the outcome to look like: list1 = [âa dogâ, âa catâ, âa mouseâ, âa rabbitâ] So that they are seperate elements rather than a joint string if that makes sense?
9 Respostas
+ 9
list1 = ["A dog, a cat", "a mouse, a rabbit"]
b=[]
for i in list1:
b+=i.split(",")
print(b)
+ 8
I would prefer the version from HonFu, but i was to late. So for the reason of showing different approaches, here is a version using a comprehension:
out1 = []
[out1.extend(i.split(', ')) for i in list1]
print(out1)
+ 3
You could make a new list, iterate through the list and append all items to the new list with the help of the split method.
+ 3
Following Seb TheS's algorithm,
list1 = ['A dog, a cat', 'a mouse, a rabbit', 'a horse']
separator, list2 = ', ', []
for e in list1:
if separator in e:
list2.extend(e.split(separator))
else:
list2.append(e)
print(list2)
+ 3
list2 = ', '.join(list1).split(', ')
+ 3
$Âąđâčđ!đšđ , just run this piece of code:
list1 = ['A dog, a cat', 'a mouse, a rabbit']
list1 = ', '.join(list1).split(', ')
print(list1)
It's exactly what Luna wanted to get as a result.
+ 2
Personally: join it into a single string, and then split it into a list.
list1 = ['A dog, a cat', 'a mouse, a rabbit']
list1 = ', '.join(list1).split(', ')
print(list1) # ['A dog', 'a cat', 'a mouse', 'a rabbit']
Edit: I realised that didn't quite answer your question in the way you asked it, but I'll leave it up to demonstrate another possible way of doing it.
0
HonFu I think your answer was not relevant to the question.
0
By simply using split function or you can google it