我有一个问题要解决,就是以特定格式填充缺失值
输入:
"_,_,30,_,_,_,50,_,_"
输出:
10,10,12,12,12,12,4,4,4
我们将从左到右填充缺失值
(10, 10, 10, _, _, _, 50, _, _)
(10, 10, 12, 12, 12, 12, 12, _, _)
(10, 10, 12, 12, 12, 12, 4, 4, 4)
我只能解决到一定程度。
s="_,_,30,_,_,_,50,_,_"
s1=s.split(",")
print(s1)
print('**************')
w=[]
for i in s1:
if i=='_':
w.append(0)
else:
w.append(int(i))
print(w)
print('*****************')
x=w[0:3]
y=w[3:]
print(x)
print('**********')
print(y)
print('***********')
avg=int(np.mean(x))
print(avg)
print('********')
c=list(map(lambda x: avg,x) )
print(c)
答案 0 :(得分:0)
您可以创建一个函数来填充(将您编写的代码模块化总是一个好主意):
from typing import List
def fill_missing_values(s: str) -> str:
s1: List[str] = s.split(',')
first_num_value: int = 0
start_at: int = s1.index('_')
end_at: int = 0
for index, value in enumerate(s1[start_at:]):
end_at = index
if value.isdigit():
first_num_value = int(value)
break
# Now you can replace values
start_at = 0 if start_at == 0 else start_at - 1
end_at += 0 if start_at == 0 else start_at + 1
previous_value: int = 0 if start_at == 0 else int(s1[start_at])
range_len: int = (end_at - start_at + 1) if start_at == 0 else (end_at - start_at + 1)
new_value: float = (first_num_value + previous_value) / range_len
for index in range(start_at, end_at+1):
s1[index] = new_value
return ','.join([str(x).replace('.0', '') for x in s1])
然后在循环中调用它:
s: str = "_,_,30,_,_,_,50,_,_"
matches = ['_,', ',_,', ',_']
index: int = 1
while any(x in s for x in matches):
s = fill_missing_values(s)
print('step {}: {}'.format(index, s)) # this is to show temporarily status, you can remove it
index += 1
print(s.split(','))
在这种情况下,我在控制台中打印了输出。
step 1: 10,10,10,_,_,_,50,_,_
step 2: 10,10,12,12,12,12,12,_,_
step 3: 10,10,12,12,12,12,4,4,4
['10', '10', '12', '12', '12', '12', '4', '4', '4']
答案 1 :(得分:-1)
你说这将是一种特殊的格式。所以我假设 30 和 50 代表索引 [2] 和索引 [7]。所以,这是我的解决方案。如果您说 30 和 50 始终存在于列表中,但它们的索引不是常量,您只需要使用 s.index()
函数来查找索引并使用该索引来获取新的计数和值。
代码如下:
s = "_,_,30,_,_,_,50,_,_"
s = s.split(",")
result = []
count = s.index('30') + 1
value = int(s[2]) / count
while count > 1:
result.append(str(int(value)))
count -= 1
value = int((value + int(s[6])) / (6 - 2 + 1))
count = 6 - 2 + 1
while count > 1:
result.append(str(value))
count -= 1
value = int(value / (len(s) - 6))
count = len(s) - 6
while count > 0:
result.append(str(value))
count -= 1
print(result)