创建循环遍历两个列表的新列表
Create new lists looping through two lists
使用两个不同的列表 A
和 B
尝试创建新列表如下:
新列表总数等于元素总数
在列表 B
.
中
每个新列都包含来自
将列表 A
中的元素与列表 B
中的元素相乘
A = [1, 2, 3, 4, 5]
B = [3, 4, 7] # list B has 3 elements, therefore 3 new lists are required
列表如下所示:
new_list1 = [3, 6, 9, 12, 15]
new_list2 = [4, 8, 12, 16, 20]
new_list3 = [7, 14, 21, 28, 35]
通过以下循环,我看到我返回了正确的值,但无法像上面那样分组到 list/dictionary。
list_dict = {}
for j in B:
for k in A:
list_dict = k * j
print(list_dict)
喜欢one-liner:
C = [list(map(lambda x: x * b, A)) for b in B]
转换为循环:
C = []
for b in B:
new_list = []
for a in A:
new_list.append(b * a)
C.append(new_list)
输出:
[
[3, 6, 9, 12, 15],
[4, 8, 12, 16, 20],
[7, 14, 21, 28, 35]
]
在您的代码中,您需要将结果存储到列表中并将该列表存储到字典中:
list_dict = {}
for j in B:
list_ = []
for k in A:
list_.append(k * j)
list_dict[j] = list_
输出:
{3: [3, 6, 9, 12, 15], 4: [4, 8, 12, 16, 20], 7: [7, 14, 21, 28, 35]}
或者您可以使用嵌套列表理解:
new_list1, new_list2, new_list3 = [[a*b for a in A] for b in B]
A = [1, 2, 3, 4, 5]
B = [3, 4, 7]
for i in B:
list=[]
for j in A:
list.append(i*j)
print(list)
output:-
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
[7, 14, 21, 28, 35]
使用两个不同的列表 A
和 B
尝试创建新列表如下:
新列表总数等于元素总数 在列表
中B
.每个新列都包含来自 将列表
中的元素相乘A
中的元素与列表B
A = [1, 2, 3, 4, 5]
B = [3, 4, 7] # list B has 3 elements, therefore 3 new lists are required
列表如下所示:
new_list1 = [3, 6, 9, 12, 15]
new_list2 = [4, 8, 12, 16, 20]
new_list3 = [7, 14, 21, 28, 35]
通过以下循环,我看到我返回了正确的值,但无法像上面那样分组到 list/dictionary。
list_dict = {}
for j in B:
for k in A:
list_dict = k * j
print(list_dict)
喜欢one-liner:
C = [list(map(lambda x: x * b, A)) for b in B]
转换为循环:
C = []
for b in B:
new_list = []
for a in A:
new_list.append(b * a)
C.append(new_list)
输出:
[
[3, 6, 9, 12, 15],
[4, 8, 12, 16, 20],
[7, 14, 21, 28, 35]
]
在您的代码中,您需要将结果存储到列表中并将该列表存储到字典中:
list_dict = {}
for j in B:
list_ = []
for k in A:
list_.append(k * j)
list_dict[j] = list_
输出:
{3: [3, 6, 9, 12, 15], 4: [4, 8, 12, 16, 20], 7: [7, 14, 21, 28, 35]}
或者您可以使用嵌套列表理解:
new_list1, new_list2, new_list3 = [[a*b for a in A] for b in B]
A = [1, 2, 3, 4, 5]
B = [3, 4, 7]
for i in B:
list=[]
for j in A:
list.append(i*j)
print(list)
output:-
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
[7, 14, 21, 28, 35]