简体   繁体   中英

How to extract values from a list and add them into a new list in python?

I have a data list like below. I need to extra all values after ":" and add those values into a new list. How can I do this?

Sample data list

list1= ['Company Name: PATRY PLC', 'Contact Name: Jony Deff', 'Company ID: 234567', 'CS ID: 236789', 'MI/MC:', 'Road Code:']

now I need to extract all the values after the colon(:) and recreate a new list like below. and also add null values for the empty strings for no values after the colon(:) like 'MI/MC:'.

new list list2 = ['PATRY PLC', 'Jony Deff', '234567', '236789', 'null', 'null']

Use split to split each item on : , and the or operator to turn the empty strings into 'null' .

>>> list1= ['Company Name: PATRY PLC', 'Contact Name: Jony Deff', 'Company ID: 234567', 'CS ID: 236789', 'MI/MC:', 'Road Code:']
>>> [i.split(':')[1] or 'null' for i in list1]
[' PATRY PLC', ' Jony Deff', ' 234567', ' 236789', 'null', 'null']
list1 = ['Company Name: PATRY PLC', 'Contact Name: Jony Deff', 'Company ID: 234567', 'CS ID: 236789', 'MI/MC:', 'Road Code:']

list2 = []

for x in list1:
    list2.append(x.split(':')[1])

print(list2)

[' PATRY PLC', ' Jony Deff', ' 234567', ' 236789', '', '']

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