English 中文(简体)
粉碎:在燃烧时添加成分。
原标题:Python: Adding element to list while iterating

我知道,它不允许在编造清单时删除内容,但允许在编造时添加名字清单的内容。 例如:

    for a in myarr:
      if somecond(a):
          myarr.append(newObj())

我已在我的法典中尝试过这一点,似乎做了一些细微的工作,但我不知道这是否是因为我只是uck,而且将来会在某些时候打破吗?

EDIT:我更喜欢不复制清单,因为“myarr”是巨大的,因此太慢。 此外,我还需要检查所附物体的“some(some)”。

EDIT:在某个时候,“某些(a)”是假的,因此不可能是无限的。

EDIT: 有些人询问了“一些cond()”功能。 每一物体的面积大小,每一物体的“部分(a)”均属实,新物体的面积将小于“部分(c)”的尺寸,如果小物体的大小太小,则该物体将返回“false”。

最佳回答

您可使用“<代码>islice,从惯用器中选取,在清单中较小部分创建代用器。 接着,你可以把条目放在名单上,而不会影响你收回的物品:

islice(myarr, 0, len(myarr)-1)

更糟的是,你甚至不必对所有这些内容进行er。 你们能够增加一个步骤规模。

问题回答

为什么不要让你去做这种事情? 这应该是防弹的,但是它赢得的却是快的。 我确信,将相关清单编入Avrepo的一个清单,因此这是一个“油漆工”算法。 但是,我倾向于不担心优化,直到显然某一部分守则确实是一个问题。 首先让它发挥作用;然后担心,如果有必要,会迅速这样做。

如果你想把所有要素推向来:

i = 0  
while i < len(some_list):  
  more_elements = do_something_with(some_list[i])  
  some_list.extend(more_elements)  
  i += 1  

如果你只想回避最初列入清单的内容:

i = 0  
original_len = len(some_list)  
while i < original_len:  
  more_elements = do_something_with(some_list[i])  
  some_list.extend(more_elements)  
  i += 1

参看rel=“noreferer” http://docs.python.org/tutorial/ Controlflow.html

It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy.

你可以这样做。

bonus_rows = []
for a in myarr:
  if somecond(a):
      bonus_rows.append(newObj())
myarr.extend( bonus_rows )

1. 直接查阅您的名单。 之后,您可以随函附上:

for i in xrange(len(myarr)):
    if somecond(a[i]):
        myarr.append(newObj())

make copy of your original list, iterate over it, see the modified code below

for a in myarr[:]:
      if somecond(a):
          myarr.append(newObj())

我今天也存在同样的问题。 我有一份需要核对的项目清单;如果这些物品通过检查,则将其列入结果清单。 如果他们didn t通过,我就把他们改成一比,如果他们(大小和大体;改动后再加一)的话,我将在名单上重新核对。

我赞成这样的解决办法。

items = [...what I want to check...]
result = []
while items:
    recheck_items = []
    for item in items:
        if check(item):
            result.append(item)
        else:
            item = change(item)  # Note that this always lowers the integer size(),
                                 # so no danger of an infinite loop
            if item.size() > 0:
                recheck_items.append(item)
    items = recheck_items  # Let the loop restart with these, if any

我的名单上确实是一个问题,或许应该采用某种方式。 但是,我的清单是小的(如10个项目),也是这样。

如果你想要在休息期间也放弃列入清单的内容,那么你可以使用一个指数和一个时段,而不是一个 lo子:

i = 0
while i < len(myarr):
    a = myarr[i];
    i = i + 1;
    if somecond(a):
        myarr.append(newObj())

扩大S.Lott的答复,以便处理新项目:

todo = myarr
done = []
while todo:
    added = []
    for a in todo:
        if somecond(a):
            added.append(newObj())
    done.extend(todo)
    todo = added

最终名单见done

备选解决办法:

reduce(lambda x,newObj : x +[newObj] if somecond else x,myarr,myarr)

假设您在本名单上最后加上<代码>arr, 你可以尝试这种方法,我经常使用。

arr = [...The list I want to work with]
current_length = len(arr)
i = 0
while i < current_length:
    current_element = arr[i]
    do_something(arr[i])
    # Time to insert
    insert_count = 1 # How many Items you are adding add the last
    arr.append(item_to_be inserted)
    # IMPORTANT!!!!  increase the current limit and indexer
    i += 1
    current_length += insert_count

这只是一纸空文,如果你这样做的话,你的方案将因fin而冻结。 除非你有此需要,否则禁止杀伤人员地雷。





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签