简体   繁体   中英

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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