简体   繁体   English

使用Python中的新元素从以前的列表中生成新列表

[英]Generating a new list from previous lists with new elements in Python

Hi i want to generate from lys1 and lys2 a new list called "lys3" that is the length of 3 that contains the (first value of lys1 * second value of lys2), (second value of lys1 * third value of lys2), (third value of lys1 * fourth value of lys2) using a loop. 嗨,我想从lys1和lys2生成一个名为“ lys3”的新列表,该列表的长度为3,其中包含(lys1的第一个值* lys2的第二个值),(lys1的第二个值* lys2的第三个值),( lys1的第三个值* lys2的第四个值)。

lys1 = [5,6,2,9]
lys2 = [3,8,3,6]
lys3 = [i * j for i in lys1 for j in lys2]
print(lys3)

this is so far the logistics i've been able to figure out, 到目前为止,这是我能够弄清的物流,

You should use zip if you want to iterate over multiple iterables simultaneously. 如果要同时迭代多个可迭代对象,则应使用zip In your case you should slice away the first element of the second iterable so you have the desired "offset" between the first and second list: 在您的情况下,您应该切掉第二个可迭代的第一个元素,以便在第一和第二个列表之间具有所需的“偏移量”:

[i * j for i, j in zip(lys1, lys2[1:])]

What you did was actually a double loop that iterated over each element in the second list for each element in the first list. 您所做的实际上是一个双循环,该循环在第二个列表中的每个元素上迭代了第一个列表中的每个元素。 Roughly equivalent to: 大致相当于:

for i in lys1:
    for j in lys2:
        ...

Which produces 16 elements. 产生16个元素。

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

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