[英]Compare tuples of different size and rearrange/Replace tuple elements in python
Hello I am new to python, looking for way of comparing two of different size tuples say for example tuple a=(3,4)
and b=(1,3,4)
compare a and b and rearrange/replace tuple b
as per tuple a
(ie) b=(3,4,1)
and it should work all different length tuples. 您好,我是python的新手,正在寻找比较两个不同大小元组的方法,例如说元组a=(3,4)
和b=(1,3,4)
比较a和b并按如下方式重新排列/替换元组b
元组a
(即) b=(3,4,1)
,它应该适用于所有不同长度的元组。
This is sample input list: 这是示例输入列表:
l=[((1, 2), (1, 2, 4)), ((1, 2, 3), (2, 3)), ((1, 3, 4), (3, 4)), ((2, 3, 4), (2, 4))]
This is my code just iterating over list of tuples: 这是我的代码,只是遍历元组列表:
for i, (a, b) in enumerate(l):
print a, b
print len(a), len(b)
I want output such that when tuple a
of length x=2
compared with tuple b
of length y=3
should rearrange/Replace tuple b as per positions of elements in tuple a and with all elements of tuple b
in it. 我想输出,使得当元组a
长度的x=2
与元组相比b
长度的y=3
应该重新排列/替换元组B中每在元组元素的位置,并与元组中的所有元素b
在它。 In other words compare tuple of shorter length with tuple of larger length and rerrange/replace the tuple of larger length tuple wrt shorter length tuple, with all element of larger tuple in it. 换句话说,将较短长度的元组与较大长度的元组进行比较,然后重新排列/替换较大长度元组的元组与较短长度元组的元组,并在其中包含较大元组的所有元素。
I want Output as: 我希望输出为:
[((1, 2), (1, 2, 4)), (( 2, 3, 1), (2, 3)), (( 3, 4, 1), (3, 4)), ((2, 4, 3), (2, 4))]
I have seen concept of sorting in python it sorts the tuples by key parameter but i couldn't find any help for comparing the tuples elements on its position element and rearranging it or replacing the whole tuple. 我已经看到了在python中进行排序的概念,它通过键参数对元组进行排序,但是我找不到比较元组元素在其position元素上并重新排列或替换整个元组的任何帮助。
I would like to have suggestions on it for resolving the issue. 我想就此问题提出建议。
I actually figured out the solution for above problem. 我实际上想出了解决上述问题的方法。 Thanks any way all for comments and feed back :) 非常感谢大家的评论和反馈:)
Input: 输入:
l=[((1, 2), (1, 2, 4)), ((1, 2, 3), (2, 3)), ((1, 3, 4), (3, 4)), ((2, 3, 4), (2, 4))]
Solution Code: 解决方案代码:
for i, (a, b) in enumerate(l):
# print a, b
# print len(a), len(b)
x= tuple(set(a).symmetric_difference(set(b)))
if(len(a)>len(b)):
new_a=b+x
l[i] = (new_a,b)
else:
new_b=a+x
l[i] = (a, new_b)
Output: 输出:
[((1, 2), (1, 2, 4)), ((2, 3, 1), (2, 3)), ((3, 4, 1), (3, 4)), ((2, 4, 3), (2, 4))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.