如何在python2.7.11中从现有列表的每一项创建列表?

2024-10-04 11:27:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从python中的列表元素生成列表。 例如:有一个包含以下信息的列表: list=['AB4', 'AB3','AC3', 'BC4', 'BC5'] 这是列表元素的确切格式。 我支持为每个元素创建列表,分别为字母(将两个字母视为一个块)和数字创建列表,这些元素将包含字符串中缺少的字符。我的意思是:

 AB:['4', '3']
 AC:['3']
 BC:['4', '5']
 4:['AB', 'BC']
 3:['AB', 'AC']
 5:['BC']

这些是我应该从原始列表生成的列表。原始列表中的元素没有限制,其格式与示例“两个字母和一个数字”完全相同。你知道吗

先谢谢你。你知道吗


Tags: 信息元素列表ab格式字母数字ac
3条回答

这个怎么样

import itertools
import operator

l = ['AB4', 'AB3','AC3', 'BC4', 'BC5']
lists = [(s[:2], s[2]) for s in l]      # [('AB', '4'), ('AB', '3'), ('AC', '3'), ('BC', '4'), ('BC', '5')]

results = dict()

for name, group in itertools.groupby(sorted(lists, key=operator.itemgetter(0)), key=operator.itemgetter(0)):
    results[name] = map(operator.itemgetter(1), group)

for name, group in itertools.groupby(sorted(lists, key=operator.itemgetter(1)), key=operator.itemgetter(1)):
    results[name] = map(operator.itemgetter(0), group)

print(results)
# Output
{   'AC': ['3'], 
    'AB': ['4', '3'], 
    'BC': ['4', '5'], 
    '3':  ['AB', 'AC'], 
    '5':  ['BC'], 
    '4':  ['AB', 'BC']}

这样就可以了:

from collections import defaultdict
l=['AB4', 'AB3','AC3', 'BC4', 'BC5']
result=defaultdict(list)
for item in l:  
    #If you want numbers to be numbers and not strings replace item[2:] with int(item[2:])  
    result[item[:2]].append(item[2:])
    result[item[2:]].append(item[:2])

你可以用这个来打印你想要的:

import pprint
pp = pprint.PrettyPrinter()
pp.pprint(result)

输出:

{'3': ['AB', 'AC'],
 '4': ['AB', 'BC'],
 '5': ['BC'],
 'AB': ['4', '3'],
 'AC': ['3'],
 'BC': ['4', '5']}

您可以使用regex(^{}模块)和^{}来实现这一点。以下内容适用于输入字符串的非数字/数字部分的任意长度:

import re
from collections import defaultdict

def str_dig(s):  # str_dig('ABC345') -> ('ABC', '345')
    return re.match('([^\d]+)(\d+)', s).groups()

lst=['AB4', 'AB3','AC3', 'BC4', 'BC5']  # do NOT shadow list!

d = defaultdict(list)
for x, y in map(str_dig, lst):  # map applies the str_dig function to all in lst
    d[x].append(y)
    d[y].append(x)

# d['AB']: ['4', '3'], d['3']: ['AB', 'AC']

相关问题 更多 >