在函数调用中拆分元组



更新:通过引用上一篇文章,我使我的最终目标更加清晰。组合元组的2D列表,然后在Python 中对其进行排序

使用以下代码行

result = list(zip(*sorted(zip(l1, l2, l3, files_good_list), section(l1), key = lambda x: float(x[0]))))

其中区段为

def section(s):
return[int(_) for _ in s.split(".")]

l1、l2、l3、files_good_list是字符串列表。

我的目标是将这四个列表组合起来,然后按l1排序。何处

l1 = ['1', '1.1', '1.2', '1.10', '2.1', '3.1', '1', '1.1', '1.2', '1.3', '1.4', '2', '2.1', '2.10', '3', '3.1', '3.2', '3.3', '3.4', '3.5', '3.6', '3.7', '3.8']

如果我使用,我的代码就能工作

result=list(zip(*排序(zip(l1,l2,l3,files_good_list),key=lambda x:float(x[0]))

但它确实将l1排序为"1"、"1.1"、"1.10"、"1.2",其中我希望l1排序为"1"、"1.1"、"1.2"、"1.10"。这就是为什么我试图使用函数部分按我想要的顺序排序。

我在这篇文章的答案中找到了类似的部分。我如何在Python中对部分编号列表进行排序?

然而,当我试图将它作为一个参数传递时,我会得到这个错误。

Traceback (most recent call last):
File "<ipython-input-422-bbd574034cbd>", line 1, in <module>
runfile('C:/Users/justin.white/Documents/Work/Regex_try.py', wdir='C:/Users/justin.white/Documents/Work')
File "C:Usersjustin.whiteAppDataLocalContinuumAnaconda3libsite-packagesspyderlibwidgetsexternalshellsitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "C:Usersjustin.whiteAppDataLocalContinuumAnaconda3libsite-packagesspyderlibwidgetsexternalshellsitecustomize.py", line 88, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "C:/Users/justin.white/Documents/Work/Regex_try.py", line 84, in <module>
result = list(zip(*sorted(zip(l1, l2, l3, files_good_list), section(l1), key = lambda x: float(x[0]))))
File "C:/Users/justin.white/Documents/Work/Regex_try.py", line 82, in section
return[int(_) for _ in s.split(".")]
AttributeError: 'list' object has no attribute 'split'

但当我做时

sorted(l1, key=section)

我没有收到错误,它按照我需要的顺序进行排序。所以我的问题是,当节在zip中时,为什么我不能将其传递到排序中?

如果你需要任何澄清,请告诉我。感谢

section接受一个包含用点分隔的整数的字符串,但在代码中,您要向它传递一个列表。一个正确的使用方法是:

result = list(zip(*sorted(zip(l1, l2, l3, files_good_list), key = lambda x: section(x[0]))))

但话说回来,我真的不确定你想对那个代码部分做什么。

一条建议是避免使用这样的一行代码,并将代码分解为可读性更强的块。这让人们很难理解你想做什么

我将为您提供一个关于您想要什么的快速示例。一节中几乎有两个部分(至少在本例中是这样)。你有x.y,其中x可以是任何数字,我假设y可以是1-10。在这种情况下,您可以制作一个自定义比较函数,将x的最大值y加权。

这样做:

l1 = ['1', '1.1', '1.2', '1.10', '2.1', '3.1', '1', '1.1', '1.2', '1.3', '1.4', '2', '2.1', '2.10', '3', '3.1', '3.2', '3.3', '3.4', '3.5', '3.6', '3.7', '3.8']
def section(s):
# Set the inital values
s1, s2 = 0, 0
# If there is a `.` then we have a subsection
if s.find('.') != -1:
s1, s2 = s.split('.')
s1, s2 = int(s1), int(s2)
# Otherwise it's whatever value is there
else:
s1 = int(s)
# Perform the actual weighting of the section and subsection
return s1*10+s2
print(sorted(l1, key=section))
# Prints ['1',
'1',
'1.1',
'1.1',
'1.2',
'1.2',
'1.3',
'1.4',
'1.10',
'2',
'2.1',
'2.1',
'2.10',
'3',
'3.1',
'3.1',
'3.2',
'3.3',
'3.4',
'3.5',
'3.6',
'3.7',
'3.8']

最新更新