请没有模块。
我有一个数字列表和一个空字符串。
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]]
答案 0 :(得分: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)
通过这种方式,您仅将逻辑应用于非空字符串。
答案 1 :(得分:0)
假设您不需要一次列出列表中的所有值。然后您可以:
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
答案 2 :(得分:0)
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]]
答案 3 :(得分:0)
这应该按照您的要求进行:删除,计算并重新插入。
在以下示例中,将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]]