Python – 从值列表中删除单位
有时,在使用Python值列表时,我们可能会遇到一个问题,即我们需要删除与值一起出现的单元。这个问题可以直接应用于日常编程和数据预处理。让我们讨论可以执行此任务的某些方式。
Input : test_list = [“54 cm”, “23 cm”, “12cm”, “19 cm”], unit = “cm”
Output : [’54’, ’23’, ’12’, ’19’]
Input : test_list = [“54 cm”], unit = “cm”
Output : [’54’]
方法 #1:使用regex()
+ 列表理解
这些功能的组合可以用来解决这个问题。在此,我们使用正则表达式仅提取数字,并删除其余的字符串单元。
Python3
# Python3 code to demonstrate working of
# Remove Units from Value List
# Using list comprehension + regex()
import re
# initializing list
test_list = ["54 kg", "23 kg", "12kg", "19 kg"]
# printing original list
print("The original list is : " + str(test_list))
# initializing unit
unit = "kg"
# Remove Units from Value List
# Using list comprehension + regex()
res = re.findall('\d+', ' '.join(test_list))
# printing result
print("List after unit removal : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove Units from Value List
# Using replace() + strip() + list comprehension
import re
# initializing list
test_list = ["54 kg", "23 kg", "12kg", "19 kg"]
# printing original list
print("The original list is : " + str(test_list))
# initializing unit
unit = "kg"
# Remove Units from Value List
# Using replace() + strip() + list comprehension
res = [sub.replace(unit, "").strip() for sub in test_list]
# printing result
print("List after unit removal : " + str(res))
输出 :
The original list is : ['54 kg', '23 kg', '12kg', '19 kg']
List after unit removal : ['54', '23', '12', '19']
方法#2:使用replace() + strip()
+ list comprehension
上述功能的组合可以用来解决这个问题。在此,我们执行用空字符串替换单元的任务,以使用 replace() 将其删除,并使用 strip() 处理杂散空格。
Python3
# Python3 code to demonstrate working of
# Remove Units from Value List
# Using replace() + strip() + list comprehension
import re
# initializing list
test_list = ["54 kg", "23 kg", "12kg", "19 kg"]
# printing original list
print("The original list is : " + str(test_list))
# initializing unit
unit = "kg"
# Remove Units from Value List
# Using replace() + strip() + list comprehension
res = [sub.replace(unit, "").strip() for sub in test_list]
# printing result
print("List after unit removal : " + str(res))
输出 :
The original list is : ['54 kg', '23 kg', '12kg', '19 kg']
List after unit removal : ['54', '23', '12', '19']