简体   繁体   English

如何使用 yield 将两个列表中的数字按索引连接到一个元组中?(Python)

[英]How can I concatenate numbers from two lists by indices into a tuple using yield?(Python)

I need to make a "generator function" which will take 2 lists and concatenate numbres from two lists by indices into a tuple.我需要制作一个“生成器函数”,它将获取 2 个列表并将两个列表中的数字按索引连接到一个元组中。 For example:例如:

l1 = [3, 2, 1]
l2 = [4, 3, 2]

The result of the first iteration will be (3, 4) The result of the second iteration will be (2, 3) And the third (1, 2) And also, one of lists may have more numbers than the other one.第一次迭代的结果将是(3, 4)第二次迭代的结果将是(2, 3)而第三次迭代(1, 2)而且,一个列表可能比另一个列表有更多的数字。 In that case I need to write condition "if one of the lists ended while iterating, then no further iterations are performed."在那种情况下,我需要编写条件“如果其中一个列表在迭代时结束,则不再执行进一步的迭代。” (using try, except ) (使用try, except

I know, that generator functions use yield instead of return , but I have no idea how to write this fuction... I did this我知道,生成器函数使用yield而不是return ,但我不知道如何编写这个函数......我这样做了

def generate_something(l1, l2):
    l3 = tuple(tuple(x) for x in zip(l1, l2))
    return l3

output is output 是

((3, 4), (2, 3), (1, 2))

It works, but this is not geterator function, there is no yield , there is no first-,second-,etc- iterations.它有效,但这不是 geterator function,没有yield ,没有第一、第二等迭代。 I hope you can help me...我希望你能帮帮我...

May be this help for you:可能对您有帮助:

def generate_something_2(l1, l2):
    # if one of the lists ended while iterating, then no further iterations are performed.
    # For this get minimal len of list
    min_i = len(l1) if len(l1) < len(l2) else len(l2)
    for i in range(0,min_i):
        yield (l1[i], l2[i])

l1 = [3, 2, 1, 1]
l2 = [4, 3, 2]

l3 = tuple(generate_something_2(l1, l2))
# Result: ((3, 4), (2, 3), (1, 2))
print(l3)

you can create your own generator:您可以创建自己的生成器:

def iterate_lists(l1,l2):
   for i,item in enumerate(l1):
       yield l1[i],l2[i]

or as a variable by generator comprehension :或者作为生成器理解的变量:

iterate_lists = (li[i],l2[i] for i,item in enumerate(l1))

about if the lengthes arent equal its not clear to me what exactly you want to do, without the message you can just go on the smaller list... just change the for i,item in enumerate(l1) with for i in range(min((len(l1),len(l2)))关于如果长度不相等,我不清楚你到底想做什么,如果没有消息,你只能在较小的列表中使用 go...只需将for i,item in enumerate(l1)更改为for i in range(min((len(l1),len(l2)))

Use a while loop and keep track of the index position, when a IndexError is raised you've hit the end of the shortest list and stop:使用 while 循环并跟踪索引 position,当出现IndexError时,您已经到达最短列表的末尾并停止:

def generate_something(l1, l2):
    idx = 0
    while True:
        try:
            yield l1[idx], l2[idx]
            idx += 1
        except IndexError:
            break


l1 = [3, 2, 1]
l2 = [4, 3, 2]

g = generate_something(l1, l2)
print(list(g))

Output: Output:

[(3, 4), (2, 3), (1, 2)]

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

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