迭代python中的子列表

R.B*_*ahl 1 python iterator list

说我有以下列表:

my_list = [2, 3, 4, 1, 44, 222, 43, 22]
Run Code Online (Sandbox Code Playgroud)

如何在不使用for循环的情况下为子列表中的所有元素分配常量值?就像是:

my_list[0:5:1] = 1 # Assign 1 to first 5 elements. This code is wrong since list requires an iterator 
Run Code Online (Sandbox Code Playgroud)

具体来说,我想为所有元素分配一个常量值,从索引开始,i直到end列表,即说

my_list[i:end] = 1 # What I would like to do. The code itself is wrong  
Run Code Online (Sandbox Code Playgroud)

关于如何在python中以最干净的方式做到这一点的任何建议?

Joe*_*Joe 6

有时2衬里比1衬里更好.

for i in range(0,5):
    my_list[i] = 0
Run Code Online (Sandbox Code Playgroud)

如果你真的想做一些混淆的东西:

这是一个单线程,无需更改原始阵列即可完成工作.

new_list = [0 if i in range(0,5) else x for x, i in zip(my_list, xrange(len(my_list)))]
Run Code Online (Sandbox Code Playgroud)

您更愿意在未知代码中遇到哪些内容?或者6个月后你自己的代码.