简体   繁体   中英

Python matching one list to dict values in another list

I have 2 lists; list one is:

a=[500,1000,1500,2000,2500,3000]

The other is like this:

z=[{'1':0},{'2':0},{'3':0},{'4':0},{'5':0}]

I have put the dicts in a list, as I want them to remain ordered, so I then run a condition:

for elems in a:
    if 2200 < elems:
        NOT SURE?

So in this condition what I want to do is, as 2200 is less than 2500 I want the value of the key number 4 in list z to increase by one.

I'm not sure how to achieve this and would like some help please.

Thanks

Here's an alternate implementation using collections.Counter:

from collections import Counter

a = [500,1000,1500,2000,2500,3000]

z = Counter(i+1 for i,v in enumerate(a) if v > 2200)
print z

print list({str(a): b} for a, b in z.iteritems())

z already is what I think is a much more useful form than the desired single-item, string-key items in the list, but as you can see, it can be converted to your preferred format again in a single line.

Output:

Counter({5: 1, 6: 1})
[{'5': 1}, {'6': 1}]

I think having z as a simple list of ints would be enough for what you want to do. Then:

z = [0, 0, 0, 0, 0]

for i, elem in enumerate(a):
    if elem > 2200:
         z[i] += 1

If you really want that one item dictionary list (assuming length of z and a is same), then you can do:

for i, elem in enumerate(a):
    if elem > 2200:
         z[i][str(i+1)] += 1

I think this should solve your problem

a = [500,1000,1500,2000,2500,3000]

from collections import defaultdict
z = defaultdict(int)

for i, elems in enumerate(a, 1):
   if 2200 < elems:
       z[i] += 1  # can cast i to str with str(i) to exactly match the keys in the example

edit, just noticed your z list wasn't zero based

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