可能是这个类似但不知怎的,我无法解决这个问题。我有一个列表列表,我想从中删除每两个元素中的一些字符,并创建另一个列表列表
list = [['A*68:02:01:03', 'A*33:01:01', '1'],
['A*68:02:01:02', 'A*33:01:01', '1'],
['A*68:02:01:01', 'A*33:01:01', '1']]
required output = [['A*68:02', 'A*33:01', '1'],
['A*68:02', 'A*33:01', '1'],
['A*68:02', 'A*33:01', '1']]
最后我想只打印独特的元素。与上述情况类似,所有三个元素都相同,因此输出应为:
output = ['A*68:02', 'A*33:01', '1']
感谢您的帮助
答案 0 :(得分:2)
>>> lst = [['A*68:02:01:03', 'A*33:01:01', '1'], ['A*68:02:01:02', 'A*33:01:01', '1'], ['A*68:02:01:01', 'A*33:01:01', '1']]
>>> newLst = [tuple(':'.join(data.split(':', 2)[:2]) for data in sublist) for sublist in lst]
>>> set(newLst)
{('A*68:02', 'A*33:01', '1')}
有趣的是':'.join(data.split(':', 2)[:2]
。将以冒号分割data
,仅取前两部分并再次加入。这样,我们在第二个冒号(包括那个)之后将所有内容都删除。
其余的只是通过嵌套列表的列表理解。我们还需要将内部列表转换为元组,因此当我们在其上调用set()
时它们是可以清除的。这样做可以消除所有重复。
答案 1 :(得分:2)
我想你想要:
lst = [['A*68:02:01:03', 'A*33:01:01', '1'],
['A*68:02:01:02', 'A*33:01:01', '1'],
['A*68:02:01:01', 'A*33:01:01', '1']]
output = []
for item in lst:
processed = [":".join(s.split(":")[:2]) for s in item]
if processed not in output:
output.append(processed)
注意:不要调用自己的变量,例如list
。
答案 2 :(得分:1)
你可以这样做:
def prefix(string):
"""
Returns the prefix of a string, including all characters
up until the second colon.
"""
return ":".join(string.split(":", 2)[:2])
def unique(iterable):
"""
Returns the unique elements in iterable, maintaining the
elements' relative order.
"""
result = []
seen = set()
for el in iterable:
if el not in seen:
seen.add(el)
result.append(el)
return result
L = [
['A*68:02:01:03', 'A*33:01:01', '1'],
['A*68:02:01:02', 'A*33:01:01', '1'],
['A*68:02:01:01', 'A*33:01:01', '1'],
]
prefixes = [(prefix(el[0]), prefix(el[1]), el[2]) for el in L]
# The built-in class set accepts an iterable and returns a set,
# an object with all duplicate elements removed. Since sets are
# unordered, converting the set back to a list will likely
# produce a list in which the original elements have lost their
# relative order.
# If this is a problem you can use the unique function from above.
uniq = list(set(prefixes))
# If you really need a list of lists, instead of a list of tuples.
uniq = [list(el) for el in uniq]
我已将您的输入列表重命名为L,因为将其命名为list
会影响内置函数列表。