Python,通过从较长的列表中删除来匹配两个列表的长度
我有两个不同长度的列表Python,通过从较长的列表中删除来匹配两个列表的长度,python,list,Python,List,我有两个不同长度的列表 list_a=[32.959723、32.9697229999995、32.97972299999999、32.98972299999999、32.9999722999999、33.00972299999999、33.01972299999985、33.0297229999998] 列表b=[35.808097,35.818096999995,35.8280969999999,35.8380969999999,35.8480969999999,35.85809699999
list_a=[32.959723、32.9697229999995、32.97972299999999、32.98972299999999、32.9999722999999、33.00972299999999、33.01972299999985、33.0297229999998]
列表b=[35.808097,35.818096999995,35.8280969999999,35.8380969999999,35.8480969999999,35.8580969999999]
我想创建一个函数来比较两个列表的长度,并从较大的列表中删除多余的值
我猜是这样的
if len(列表a)!=len(列表b):
#代码来匹配它们。
您只需找到最小长度,并以此大小对两个列表进行切片(最大的将被切片,最小的将保留所有)
如果您关心“不必要时不应用计算”,您可以使用以下条件:
if len(list_a) < len(list_b):
list_b = list_b[:len(list_a)]
elif len(list_a) > len(list_b):
list_a = list_a[:len(list_b)]
如果len(列表a)len(列表b):
列表a=列表a[:len(列表b)]
通过比较长度,可以使用切片功能
如果您只考虑列表的大小,即不关心其中的数据,则可以使用以下代码:
def compare_and_match(list_a, list_b):
len_a = len(list_a)
len_b = len(list_b)
if len_a > len_b:
list_a = list_a[:len_b]
elif len_a < len_b:
list_b = list_b[:len_a]
return list_a, list_b
list_a = [32.959723, 32.969722999999995, 32.97972299999999,
32.98972299999999, 32.99972299999999,
33.00972299999999, 33.019722999999985, 33.02972299999998]
list_b = [35.808097, 35.818096999999995, 35.82809699999999,
35.83809699999999, 35.84809699999999, 35.85809699999999]
list_a, list_b = compare_and_match(list_a, list_b)
你是说两个列表中的值相同吗?这是使用电视机的好时机。您可以使用类似于“set\u a=set(list\u a)set\u b=set(list\u b)leverts=set\u a.difference(set\u b)”的方式。这是一个可能的副本,请更具体一些。是否要随机删除值?
if len(list_a) < len(list_b):
list_b = list_b[: len(list_a)]
elif len(list_a) > len(list_b):
list_a = list_a[: len(list_b)]
list_a = [32.959723, 32.969722999999995, 32.97972299999999, 32.98972299999999, 32.99972299999999, 33.00972299999999]
list_b = [35.808097, 35.818096999999995, 35.82809699999999, 35.83809699999999, 35.84809699999999, 35.85809699999999]
def compare_and_match(list_a, list_b):
len_a = len(list_a)
len_b = len(list_b)
if len_a > len_b:
list_a = list_a[:len_b]
elif len_a < len_b:
list_b = list_b[:len_a]
return list_a, list_b
list_a = [32.959723, 32.969722999999995, 32.97972299999999,
32.98972299999999, 32.99972299999999,
33.00972299999999, 33.019722999999985, 33.02972299999998]
list_b = [35.808097, 35.818096999999995, 35.82809699999999,
35.83809699999999, 35.84809699999999, 35.85809699999999]
list_a, list_b = compare_and_match(list_a, list_b)
>>> list_a
[32.959723,
32.969722999999995,
32.97972299999999,
32.98972299999999,
32.99972299999999,
33.00972299999999]
>>> list_b
[35.808097,
35.818096999999995,
35.82809699999999,
35.83809699999999,
35.84809699999999,
35.85809699999999]