![](/img/trans.png)
[英]Concatenate each element in a nested list with all elements in another nested list
[英]How to get into each element in a nested list and compare it with the equivalent in all elements in another list?
我需要进入嵌套列表中的每个元素,并将其与另一个列表中所有元素中的等效元素进行比较。
我有两个嵌套列表:
磅=
[[1, 0, 1, 0],
[1, 1, 1, 1],
[0, 0, 1, 0]]
LK=
[[1, 0, 1, 0],
[0, 0, 1, 1],
[1, 1, 1, 1],
[0, 0, 1, 0],
[1, 1, 0, 0],
[0, 0, 0, 0] ]
分析流程:
我从 LK 中取出第一个子列表(即 [1, 0, 1, 0])并将其各个元素(即 1, 0, 1, 0)与子列表 LB [1, 0, 1, 0]、[1、1、1、1] 和 [0、0、1、0]。 然后我从 LK 中取出第二个子列表(即 [0, 0, 1, 1])并将其各个元素(即 0, 0, 1, 1)与 LK 子列表 [1, 0, 1, 0], [1, 1, 1, 1, 1], 和 [0, 0, 1, 0] 然后我从 LK 中取出第三个子列表(即 [1, 1, 1, 1])并进行比较它的各个元素(即 1, 1, 1, 1)以及 LB 子列表 [1, 0, 1, 0]、[1, 1, 1, 1, 1] 和 [0, 0, 1, 0]
这是我对代码的尝试,但我知道它不能正常工作并且不包含所有条件。
for i in LK, LB:
for j in i:
while j < (len(LK)-1):
if j == 0:
j += 1
elif j != 0:
i += 1
else:
print(LB[i])
附加条件:
我们对列表 LB 中的所有元素执行这样的迭代,将它们与来自 LK 的子列表进行比较。
在比较期间分析的示例中:
Output: Displayed LB sublists that limited (LB子列表可以显示在几个扇区)
我对你到底想要什么 output 有点困惑,但如果你只想 output 哪些列表是相等的,这很容易完成,不需要遍历每个元素:
for lk_row_index, lk_row in enumerate(LK):
for lr_row_index, lr_row in enumerate(LR):
if lk_row != lr_row:
print(f"LR row {lr_row_index} is not equal to LK row {lk_row_index}")
else:
print(f"LR row {lr_row_index} is equal to LK row {lk_row_index}")
这很丑陋,但它有效。 看不到对匹配条件进行编码的好方法。
遍历 LK,对于每个 LK 遍历 LB。 如果列表“匹配”则打印
LB=[[1, 0, 1, 0],
[1, 1, 1, 1],
[0, 0, 1, 0]]
LK=[[1, 0, 1, 0],
[0, 0, 1, 1],
[1, 1, 1, 1],
[0, 0, 1, 0],
[1, 1, 0, 0],
[0, 0, 0, 0] ]
def mch(str1,str2):
x=0
while x+1 < len(str1)
if str1[x] == 0:
if not str2[x] == 0: # 0 not in both strings
return False
if x < (len(str1)-1): #if both strins are 0 possible match only
# if strings match at next position
# only do check if there is a next position
if str1[x+1] == str2[x+1]:
x+=1
else:
return False
x+=1
return True
for str1 in LK:
print("\n\n","Matches for ", str1, "\n")
for str2 in LB:
if mch(str1,str2)
print(str2)
如果 LK 的子列表与 LB 的多个子列表匹配,我不清楚你想做什么,但如果你只有一个副本,那么我认为这就是你想要的:
[B_list for B_list in LB if any(
all(
k_item!=0 or b_item==0 for k_item, b_item in zip(B_list, K_list)
)
for K_list in LK
)
]
第 1 行迭代 LB,第 5 行迭代 LK。 第 3 行检查所选子列表的相应元素是否在特定位置匹配,第 2 行检查它们是否在整个子列表中匹配。 然后第 1 行末尾的any
检查对于 LB 的特定子列表,是否存在任何有效的 LK 子列表。 因此,这将返回 LB 的所有子列表,其中存在 LK 的任何子列表,对于所有位置,对应的元素都匹配。
Output:
[[1, 0, 1, 0], [1, 1, 1, 1], [0, 0, 1, 0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.