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']
CodePudding user response:
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']
CodePudding user response:
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']
CodePudding user response:
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.