my_list = [0, 219, 211, 212, 212]
Run Code Online (Sandbox Code Playgroud)
我需要以这种方式对项目进行求和:
item + item,(item + item)+ item,(item + item + item)+ Item ...
0 + 219,(219)+ 211,(430)+212,(641)+212
为了更清楚,这是我需要得到的总和:
new_list = [219, 430, 641, 853]
Run Code Online (Sandbox Code Playgroud)
我认为解决方案可能是列表理解,这样的东西只返回每个项目与下一个项目的总和.
[(x + y) for (x, y) in zip(my_list[:-1], my_list[1:])]
Run Code Online (Sandbox Code Playgroud)
任何的想法?
我想创建一个函数,它返回奇数位置列表元素或列表的负元素.
我的解决方案适用于第一个断言,但第二个生成AssertionError,因为返回[-1,-2,1]而不是[-1,-2].有什么建议?
def solution(input):
output = []
for item in input:
if item < 0:
output.append(item)
elif not item % 2 == 0:
output.append(item)
return output
assert solution([0,1,2,3,4,5]) == [1,3,5]
assert solution([1,-1,2,-2]) == [-1,-2]
Run Code Online (Sandbox Code Playgroud) 我想用不同的值(从字典中)替换字符串的出现.
string = 'asfd @@@ fdsfd @@@ ffds @@@ asdf'
kv = {1: 'hi', 2: 'there', 3: 'bla'}
Run Code Online (Sandbox Code Playgroud)
预期:
string = 'asfd hi fdsfd there ffds bla asdf'
Run Code Online (Sandbox Code Playgroud)
我已经尝试了几种解决方案,特别是.replace或re.sub,但仍然找不到好的解决方案.