开发者

linking two lists together with an iterator function in python

开发者 https://www.devze.com 2023-01-28 07:08 出处:网络
i have two lists, both with 128 items: a= [0, 1, 2, 3, ...] b= [6.4, 53.8, -5.2, 7.1, ...] i have to run list b through two checks:

i have two lists, both with 128 items:

a= [0, 1, 2, 3, ...] b= [6.4, 53.8, -5.2, 7.1, ...]

i have to run list b through two checks:

  1. is b[n]>50.0
  2. is b[n]<0

if check1 is true, than b[n]=b[n]-50, AND a[n]=a[n]+1 if check2 is true, than b[n]=b[n]+100, AND a[n]开发者_开发问答=a[n]-1

i can't figure out how to tie the two items in each list together so that a change in list b[n] triggers a change also in list a[n]

using this example, after running these lists through the 2 checks:

a= [0, 2, 1, 3, ...] b= [6.4, 3.8, 94.8, 7.1, ...]

i'm only weeks into programming with python and i have absolutely no previous experience with coding. i've been reading about iterators, maps, for loops, etc but i can't seem to get the language right for this sequence.

it seems easy but i'm stuck!

thanks,

joel.


Produce pairs of corresponding items from the two lists with zip and process each pair. You can use a generator comprehension to get all the processed pairs, and zip again to get lists back.

def process(a, b):
    if b > 50:
        a += 1
        b -= 50
    elif b < 0:
        a -= 1
        b += 100
    return (a, b)

def process_all(as, bs):
    # Notice the '*' here. 'zip' takes multiple arguments;
    # the '*' forces evaluation of the generator, and expands the resulting
    # sequence into several arguments.
    return zip(*(process(a, b) for (a, b) in zip(as, bs)))


Is there anything wrong with just

for i in range(len(a)):
    if b[i] > 50.0:
        b[i] -= 50.0
        a[i] += 1
    elif b[i] < 0.0:
        b[i] += 100.0
        a[i] -= 1
0

精彩评论

暂无评论...
验证码 换一张
取 消