简体   繁体   中英

Python: turn one item in list into two items

First thanks in advance , still pretty new to python.

I have the following list:

GroceryList = ['apples', 'oranges', 'strawberries and grapes', 'blueberries']

I have tried using .replace with the code:

GroceryList = [f.replace('and', '\'' + ',' + '\'') for f in GroceryList]

This replaces 'and' but the output after I print the list is:

['apples', 'oranges', "strawberries ',' grapes", 'blueberries']

This leaves two quotation marks creating another list at four items instead of the intended five. Does anyone know why? (In your explanation, if possible, could you also explain what I am doing wrong?)

Use str.split and str.join here:

>>> GroceryList = ['apples', 'oranges', 'strawberries and grapes', 'blueberries']
>>> [", ".join(x.split(' and ')) for x in GroceryList]
['apples', 'oranges', 'strawberries, grapes', 'blueberries']

or may be you wanted this:

>>> [y  for x in GroceryList for y in x.split(' and ')]
['apples', 'oranges', 'strawberries', 'grapes', 'blueberries']

str.split splits a string at the sep passed to it (or by default at any whitespace) and return a list.

>>> strs = 'strawberries and grapes'
>>> strs.split(' and ')
['strawberries', 'grapes']

Adding a , between two words using str.replace in a string doesn't makes it two different string, you simply modified that string and added a comma character in it.

A similar approach would be to use ast._literal_eval but recommended here.

But this requires the words to have quotes around them.

Example:

>>> from ast import literal_eval
>>> strs = '"strawberries" and "grapes"' 
>>> literal_eval(strs.replace('and', ',')) # replace 'and' with a ','
('strawberries', 'grapes')                 #returns a tuple

The problem is that you are manually altering the string to look like two separate list items. This is not the same as splitting the string into multiple objects. Use the str.split method for that.

new_grocery_list = []
for item in GroceryList:
    new_grocery_list.extend(item.split(' and '))
print(new_grocery_list)

You can also do all this at once, in a list comprehension. However, it's a little less intuitive to read, so personally I prefer the explicit loop in this case. Readability counts!

new_grocery_list = [subitem for item in GroceryList for subitem in item.split(' and ')]
print(new_grocery_list)

Could use the following to only split on and as a word, and join it back together after...

from itertools import chain
import re

GroceryList = ['apples', 'oranges', 'strawberries and grapes', 'blueberries']
new_stuff = list(chain.from_iterable(re.split(r'\b\s*and\s*\b', el) for el in GroceryList))
# ['apples', 'oranges', 'strawberries', 'grapes', 'blueberries']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM