简体   繁体   English

我如何通过选择然后删除每个项目来迭代 python 列表?

[英]How can I iterate on python list by choosing and then removing each item?

So I have this dict i take from some page using request.所以我有这个字典是我使用请求从某个页面上获取的。 Now i use its values to create list.现在我使用它的值来创建列表。 How can I iterate on that list to extract and use each item?我如何迭代该列表以提取和使用每个项目? I have already tried something like this:我已经尝试过这样的事情:

  for component in values:
        if values.index(component) > 0:
            value = values.pop()

but its give me only some items and leave others.但它只给我一些物品而留下其他物品。

It looks like you only need to iterate over the list, not remove any elements.看起来您只需要遍历列表,而不是删除任何元素。 If you want to create a list from an existing one, you can use the list comprehension:如果要从现有列表创建列表,可以使用列表理解:

same_values = [x for x in values]

And if you want, you can add a specific condition:如果需要,您可以添加特定条件:

positive_values = [x for x in values if x > 0]

Given, you got a dictionary and need the values in the form of a list.给定,你有一本字典,需要列表形式的值。 Let dct be your dictionary, then extract the values from the dictionary...dct成为你的字典,然后从字典中提取值......

list_values = list( dct.values() )

If you want to filter the values based on the index of the dictionary, then you can use the below code to filter the values based on the index from the dictionary.如果要根据字典的索引过滤值,则可以使用以下代码根据字典中的索引过滤值。

for i, j in zip( dct.keys(), dct.values() ):
    if i > 0:
        print(j)

The functions keys() and values() returns the indexes and values at that index separately, which are joined using the zip function and stored into i and j respectively at each iteration of the for-loop.函数 keys() 和 values() 分别返回该索引处的索引和值,它们使用 zip function 连接起来,并在 for 循环的每次迭代中分别存储到ij中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM