我有两份名单。一个包含组件的名称,另一个包含组件的名称,并将它们描述为字符串。我需要使用组件列表对描述列表进行排序,以便它们具有相同的顺序。
components = ['R500','R501','C500','C501','C502','R500']
description =['R500 "RES 1k 1% 0603"','R500 "RES 1k 1% 0603"','R508 "RES 9k 1% 06013"','R501 "RES 10k 1% 0604"','C500 "1uF 10% 0805"','C501 10uF 10% 0806','C502 "1nF 10% 0807"']R508应该被丢弃,因为它不在组件列表中。
描述列表中的C501被故意格式化不同,因为格式并不总是相同的。
我期望的产出是;
description = [
'R500 "RES 1k 1% 0603"',
'R501 "RES 10k 1% 0604"',
'C500 "1uF 10% 0805"',
'C501 "10uF 10% 0806"',
'C502 "1nF 10% 0807"',
'R500 "RES 1k 1% 0603",]发布于 2019-08-08 11:08:21
你可以用这个:
description.sort(key=lambda x:components.index(x.split(' "')[0]))但是,这将不适用于当前的示例,因为组件中没有R508。另外,R500出现了两次,所以它使用了第一次出现。
我想你可能想要的是:
def findBySubstring(descriptions, sub):
for d in descriptions:
if sub in d:
return d
return "No description found"
result = [findBySubstring(descriptions, c) for c in components]发布于 2019-08-08 11:06:22
示例数据包含一些不以组件中的任何字符串开头的值,因此此实现将它们放在排序列表的开头。如果要引发此条件的异常,则可以使用代码的注释部分。
def find_startswith_index(value, indexes=components):
for i, component in enumerate(components):
if value.startswith(component):
return i
return -1
# raise IndexError(f'Sort key not found for value "{value}"')
sorted(description, key=find_startswith_index)
# ['R508 "RES 9k 1% 06013"', 'R500 "RES 1k 1% 0603"', 'R500 "RES 1k 1% 0603"', 'R501 "RES 10k 1% 0604"', 'C500 "1uF 10% 0805"', 'C501 "10uF 10% 0806"', 'C502 "1nF 10% 0807"']https://stackoverflow.com/questions/57411040
复制相似问题