如何使用python删除循环列表中的元素,直到只剩一个元素? [英] How to delete elements of a circular list until there is only one element left using python?

查看:439
本文介绍了如何使用python删除循环列表中的元素,直到只剩一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何遍历1-100之间的列表,在该列表中删除从第一个元素开始的所有其他元素,并重复该步骤,直到列表中仅剩一个元素为止.我是否必须使用循环链表,还是可以仅使用循环和条件语句来完成它?

How would I go about iterating through a list from 1-100, where I delete every other element starting with the first element, and repeat that step until there in only one element left in the list. Would I have to use a circular linked list, or can it be done just using loops and conditional statements?

推荐答案

如果采用循环列表结构,则在删除列表的最后一个元素时,要删除的下一个元素不是其余列表中的第一个元素除了第二个.因此,

If you assume the circular list structure, when the last element of the list is deleted, the next element to be deleted is not the first one in the remaining list any more but the second one. Thus,

L = range(100)
st1=len(L)%2
st2=0
while len(L)>1:
    del L[st2::2]
    st2=(st1+st2)%2
    st1=len(L)%2
    print L

应该是正确的.

结果是

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
[3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63, 67, 71, 75, 79, 83, 87, 91, 95, 99]
[7, 15, 23, 31, 39, 47, 55, 63, 71, 79, 87, 95]
[7, 23, 39, 55, 71, 87]
[7, 39, 71]
[7, 71] 
[71]

这篇关于如何使用python删除循环列表中的元素,直到只剩一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆