Seb*_*her 0 indexing list python-3.x
我的目标是遍历列表并返回列表中的每个元素,每次迭代的当前索引除外。
例如:
my_list = [1,2,3]
应该返回:
>>>[2,3]
>>>[1,3]
>>>[1,2]
Run Code Online (Sandbox Code Playgroud)
我已经尝试创建一个 for 循环来创建列表的副本,从副本中弹出当前索引并返回它。
my_list = [1,2,3]
for a in my_list:
the_index = my_list.index(a)
print(my_list.copy().pop(the_index))
Run Code Online (Sandbox Code Playgroud)
返回
>>>1
>>>2
>>>3
Run Code Online (Sandbox Code Playgroud)
关于如何正确实施这一点的任何想法?
以下看起来相当简单:
lst = [1,2,3]
[lst[:i] + lst[i+1:] for i in range(len(lst))]
# [[2, 3], [1, 3], [1, 2]]
Run Code Online (Sandbox Code Playgroud)
或者对于循环打印:
for i in range(len(lst)):
print(lst[:i] + lst[i+1:])
# [2, 3]
# [1, 3]
# [1, 2]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
604 次 |
| 最近记录: |