[英]How to remove string within a mixed list and place it back again?
请不要模块。
我有一个数字列表和一个空字符串列表。
new_lst = [['', 0.0, 0.1, 0.2] , ['', '', 0.2 , 0.3], [0.1, 0.1, 0.2, 0.3]]
我用了
lst = [x for x in lst if x!= '']
去除 ''。
在此之后我有一堆计算,所以我需要删除''(除非有其他方法进行计算并忽略所有str?)。 在这些计算之后,我希望能够在删除''的任何地方插入'',而不必像这样输入索引:
new_lst[:1].insert(0, '')
我需要一个代码,可以找到''被删除的地方,然后插入'到该索引中。
new_lst = []
for i in range(3):
lst = ['', 0.0, 0.1, 0.2] , ['', 0.1, 0.2, 0.3], [0.1, 0.1, 0.2, 0.3]]
lst = [x for x in lst if x!= '']
#do calculations here . for example, for x in lst, add 1.0
new_lst.append(lst)
new_lst[:1].insert(0, '')
print(new_lst)
#expected output:
new_lst = [['', 1.0, 1.1, 1.2] , ['', '', 1.2, 1.3], [1.1, 1.1, 1.2, 1.3]]
您可以使用列表理解:
def logic_func(x):
return x+ 1.0
single_lst = ['', 0.0, 0.1, 0.2]
new_single_lst = [logic_func(x) if x != '' else x for x in single_lst]
print(new_single_lst)
这样,您只将逻辑应用于非空字符串。
假设您不需要一次列表中的所有值。 那么你也能:
lists = [['', 0.0, 0.1, 0.2], ['', 0.1, 0.2, 0.3], [0.1, 0.1, '', 0.2, 0.3]]
for lst in lists:
try:
split_index = lst.index('')
first_part = lst[:split_index]
second_part = lst[split_index + 1:]
# perform calculation
# join lists again and insert the quotes in the correct place
new_list = first_part + [''] + second_part
except ValueError:
# no need to split and join here, you can just use the complete list
# perform calculation
new_list = lst
def fun(a):
# performing mathematical offeration on east sublist
return [i+1 if i!='' else i for i in a]
lst = [['', 0.0, 0.1, 0.2] , ['', 0.1, 0.2, 0.3], [0.1, 0.1, 0.2, 0.3]]
new_list = list(map(lambda x: fun(x),lst))
print(new_list)
产量
[['', 1.0, 1.1, 1.2], ['', 1.1, 1.2, 1.3], [1.1, 1.1, 1.2, 1.3]]
这应该按照您的要求执行:删除,计算和插入。
在以下示例中,我为每个值添加max和min:
new_lst = [['', 0.0, 0.1, 0.2] , ['', '', 0.2 , 0.3], [0.1, 0.1, 0.2, 0.3]]
def foo(subl):
# get indxes and remove empty strings
indx = [i for i, x in enumerate(subl) if x == ""]
subl = list(filter(lambda x: x != "", subl))
# do calculations here
M, m = max(subl), min(subl)
subl = [x + (M+m) for x in subl]
# empty strings back
[subl.insert(i, "") for i in indx]
return subl
new_lst = [foo(subl) for subl in new_lst]
new_lst
输出:
[['', 0.2, 0.30000000000000004, 0.4],
['', '', 0.7, 0.8],
[0.5, 0.5, 0.6000000000000001, 0.7]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.