从python 2.7中的列表中删除每个第n个元素 [英] deleting every nth element from a list in python 2.7

查看:58
本文介绍了从python 2.7中的列表中删除每个第n个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被赋予了创建代码的任务.任务如下:

I have been given a task to create a code for. The task is as follows:

你是一艘帆船的船长,你和你的船员有被海盗抓获.海盗船长让你们都站着在他的船甲板上的一个圆圈中试图决定按哪个顺序你应该走木板.最终他决定了以下几点方法:

You are the captain of a sailing vessel and you and your crew have been captured by pirates. The pirate captain has all of you standing in a circle on the deck of his ship trying to decide in which order you should walk the plank. Eventually he decides on the following method:

(a) 海盗船长让你选择一个数字 N.

(a) The pirate captain asks you to pick a number N.

(b)第一个走木板的人将是第 N 个人(从你).

(b) The first person to walk the plank will be the Nth person (starting from you).

(c) 然后队长将继续绕圈强迫每第 N 个走木板的人.

(c) The captain will then continue around the circle forcing every Nth person to walk the plank.

(d) 一旦只有一个人离开,那个人将获得自由.

(d) Once there is only one person left, that person will be given freedom.

例如:船员包括:安德鲁、布伦达、克雷格、戴德雷、爱德华、费利西蒂、格雷格和哈丽特.Andrew 选择 N=2.船员将按照以下顺序走木板:布伦达、戴德、菲丽西蒂、哈丽特、克雷格、格雷格、爱德华.安德鲁将给予自由.

For example: The crew consists of: Andrew, Brenda, Craig, Deidre, Edward, Felicity, Greg and Harriet. Andrew selects N=2. The crew will walk the plank in the order: Brenda, Deidre, Felicity, Harriet, Craig, Greg, Edward. Andrew will be given freedom.

我到目前为止的代码是:

The code i have so far is:

def survivor(names, step):
    names =  ["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"]
    Next = step - 1
    names.pop(Next)
    print names

这将从列表中删除第 n 个人,但我不确定如何遍历列表以继续删除第 n 个人.

This will remove the first nth person from the list but I'm not sure how to loop through the list to keep removing the nth person.

我需要它,所以让我们假设 step = 3,然后我需要它来删除 craig,然后从 craig 开始计数并删除下一个第三个元素,即 felicity,依此类推,直到只剩下一个人为止.

I need it so lets assume step = 3, then i need it to remove craig and then count from craig onwards and remove the next 3rd element which is felicity and so on until there is one person left.

我该怎么做?

推荐答案

这似乎有效:

from collections import deque
def survivor(names, step):     
    circle = deque(names)
    while len(circle) > 1:
        circle.rotate(1-step)
        print circle.popleft()
    return circle[0]

它打印海盗受害者的名字并返回幸存者的名字:

It prints the names of the pirate's victims and returns the name of the survivor:

In [17]: crew = ["Andrew", "Brenda", "Craig", "Deidre",
   ....: "Edward", "Felicity", "Greg", "Harriet"]

In [18]: survivor(crew, 2)
Brenda
Deidre
Felicity
Harriet
Craig
Greg
Edward
Out[18]: 'Andrew'

In [19]: survivor(crew, 3)
Craig
Felicity
Andrew
Edward
Brenda
Harriet
Deidre
Out[19]: 'Greg'

这篇关于从python 2.7中的列表中删除每个第n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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