'Split Python list field into two and leave them in place
How would you split a field in Python and then leave the two fields side by side in the list? Is there a command to use asides from .split()? Or would it make more sense to write a function that does this? How would it be done across multiple lists
Performance is not a major concern. Below is an example of what I'm trying to accomplish.
Edit: I don't mind using split(), I just wanted to know how something like this could be implemented.
List before formatting
['Intel', 'Core', 'i5-4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
List after formatting
['Intel', 'Core', 'i5', '4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
Solution 1:[1]
Here is one way to do so, using list comprehension and split():
data = ['Intel', 'Core', 'i5-4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
new_data = [element for item in data for element in item.split("-")]
print(new_data) # ['Intel', 'Core', 'i5', '4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
The equivalent with for loops would be:
new_data = []
for item in data:
for element in item.split("-"):
new_data.append(element)
print(new_data) # ['Intel', 'Core', 'i5', '4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
Solution 2:[2]
List comprehensions to the rescue.
data = ['Intel', 'Core', 'i5-4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
result = [y for x in data for y in x.split('-')]
# ['Intel', 'Core', 'i5', '4210Y', '@', '1.50GHz', '(20%)', '998', 'N']
Solution 3:[3]
I would suggest doing something like
string = '-'.join(list)
list = string.spit('-')
Which would work fine here, although alternaively you could use the list.insert(item, index) method if this way causes problems.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cubix48 |
| Solution 2 | Chris |
| Solution 3 | Jacob |
