英文:
Is there a way to simplify this function and how does this may look like?
问题
我是一个完全的新手,需要一些帮助:
我将始终将一个二维嵌套列表输入到这个函数中。
def CombineAttributes(AttributeList):
NumAttributes = len(AttributeList)
print("Got the following AttributeList: {} , it has got {} Attributes in it and im going to Combine Everything now".format(AttributeList, NumAttributes))
if(NumAttributes > 10):
print("MAXIMUM NUMBER OF 10 ATTRIBUTES REACHED")
elif(NumAttributes == 1):
List = [str(a) for a in AttributeList[0]]
elif(NumAttributes == 2):
List = [[str(a)+str(b) for a in AttributeList[0]] for b in AttributeList[1]]
elif(NumAttributes == 3):
List = [[str(a)+str(b)+str(c) for a in AttributeList[0]] for b in AttributeList[1] for c in AttributeList[2]]
# ... (继续下面的elif分支,直到NumAttributes等于10)
print("Im going to return the following after ive combined everything: {}".format(List))
return List
示例输入调用:
List = [['a','b','c','d'],[1,2,3,4]]
CombineAttributes(List)
这个调用的输出:
Got the following AttributeList: [['a', 'b', 'c', 'd'], [1, 2, 3, 4]] , it has got 2 Attributes in it and im going to Combine Everything now
Im going to return the following after ive combined everything: [['a1', 'b1', 'c1', 'd1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3'], ['a4', 'b4', 'c4', 'd4']]
如果我能够删除最大数量的属性(NumAttributes)并且能够删除一堆“if”和“elif”以便通过循环遍历列表将其缩短成几行,我会感到高兴。
请评论我代码或问题的理解是否有误。我很期待您的回答。
英文:
I'm a total noob and I need some help here:
I will always input (into AttributeList) a 2 dimensional nested list into this function.
def CombineAttributes(AttributeList):
NumAttributes = len(AttributeList)
print("Got the following AttributeList: {} , it has got {} Attributes in it and im going to Combine Everything now".format(AttributeList, NumAttributes) )
if( NumAttributes > 10):
print("MAXIMUM NUMBER OF 10 ATTRIBUTES REACHED")
elif( NumAttributes == 1 ):
List = [str(a) for a in AttributeList[0]]
elif( NumAttributes == 2 ):
List = [[str(a)+str(b) for a in AttributeList[0]] for b in AttributeList[1]]
elif( NumAttributes == 3 ):
List = [[str(a)+str(b)+str(c) for a in AttributeList[0]] for b in AttributeList[1] for c in AttributeList[2]]
elif( NumAttributes == 4 ):
List = [[str(a)+str(b)+str(c)+str(d) for a in AttributeList[0]] for b in AttributeList[1] for c in AttributeList[2] for d in AttributeList[3]]
elif( NumAttributes == 5 ):
List = [[str(a)+str(b)+str(c)+str(d)+str(e) for a in AttributeList[0]] for b in AttributeList[1] for c in AttributeList[2] for d in AttributeList[3] for e in AttributeList[4]]
elif( NumAttributes == 6 ):
List = [[str(a)+str(b)+str(c)+str(d)+str(e)+str(f) for a in AttributeList[0]] for b in AttributeList[1] for c in AttributeList[2] for d in AttributeList[3] for e in AttributeList[4] for f in AttributeList[5]]
elif( NumAttributes == 7 ):
List = [[str(a)+str(b)+str(c)+str(d)+str(e)+str(f)+str(g) for a in AttributeList[0]] for b in AttributeList[1] for c in AttributeList[2] for d in AttributeList[3] for e in AttributeList[4] for f in AttributeList[5] for g in AttributeList[6]]
elif( NumAttributes == 8 ):
List = [[str(a)+str(b)+str(c)+str(d)+str(e)+str(f)+str(g)+str(h) for a in AttributeList[0]] for b in AttributeList[1] for c in AttributeList[2] for d in AttributeList[3] for e in AttributeList[4] for f in AttributeList[5] for g in AttributeList[6] for h in AttributeList[7]]
elif( NumAttributes == 9 ):
List = [[str(a)+str(b)+str(c)+str(d)+str(e)+str(f)+str(g)+str(h)+str(i) for a in AttributeList[0]] for b in AttributeList[1] for c in AttributeList[2] for d in AttributeList[3] for e in AttributeList[4] for f in AttributeList[5] for g in AttributeList[6] for h in AttributeList[7] for i in AttributeList[8]]
elif( NumAttributes == 10 ):
List = [[str(a)+str(b)+str(c)+str(d)+str(e)+str(f)+str(g)+str(h)+str(i)+str(j) for a in AttributeList[0]] for b in AttributeList[1] for c in AttributeList[2] for d in AttributeList[3] for e in AttributeList[4] for f in AttributeList[5] for g in AttributeList[6] for h in AttributeList[7] for i in AttributeList[9] for j in AttributeList[10]]
print("Im going to return the following after ive combined everything: {}".format(List))
return List
example input call:
List = [['a','b','c','d'],[1,2,3,4]]
CombineAttributes(List)
output of this call:
Got the following AttributeList: [['a', 'b', 'c', 'd'], ['1', '2', '3', '4']] , it has got 2 Attributes in it and im going to Combine Everything now
Im going to return the following after ive combined everything: [['a1', 'b1', 'c1', 'd1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3'], ['a4', 'b4', 'c4', 'd4']]
I would be happy if i would be able to remove the maximum amount of Attributes (NumAttributes) and if i could remove the bunch of "if's" and "elif's" to shorten it into a couple of lines by looping through the list.
Please comment misunderstandings of my code or my question. Im curious about your answeres.
答案1
得分: 1
你可以在这里使用itertools的product函数来生成合并后的数据。请注意,返回的对将是列表中的元组,而不是列表。
def CombineAttributes(data):
print(f"得到以下属性列表: {data} 共有 {len(data)} 个属性,现在我要合并所有内容")
merged = [[]]
for pair in product(*data[::-1]):
if len(merged[-1]) == len(data[0]):
merged.append([])
merged[-1].append("".join(str(ele) for ele in pair[::-1]))
merged.sort()
print("合并完成后,我将返回以下内容:", merged)
return merged
data = [['a', 'b', 'c', 'd'], [1, 2, 3, 4]]
CombineAttributes(data)
data1 = [['a', 'b'], [1, 2], ['W', 'X']]
CombineAttributes(data1)
输出
得到以下属性列表: [['a', 'b', 'c', 'd'], [1, 2, 3, 4]] 共有 2 个属性,现在我要合并所有内容
合并完成后,我将返回以下内容: [['a1', 'b1', 'c1', 'd1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3'], ['a4', 'b4', 'c4', 'd4']]
得到以下属性列表: [['a', 'b'], [1, 2], ['W', 'X']] 共有 3 个属性,现在我要合并所有内容
合并完成后,我将返回以下内容: [['a1W', 'b1W'], ['a1X', 'b1X'], ['a2W', 'b2W'], ['a2X', 'b2X']]
英文:
You can use itertools product here to generate your merged data. note that the pair returned will be tuple in the list rather then lists.
def CombineAttributes(data):
print(f"Got the following AttributeList: {data} its got {len(data)} Attributes in it and im going to Combine Everything now")
merged = [[]]
for pair in product(*data[::-1]):
if len(merged[-1]) == len(data[0]):
merged.append([])
merged[-1].append("".join(str(ele) for ele in pair[::-1]))
merged.sort()
print("Im going to return the following after ive combined everything:", merged)
return merged
data = [['a', 'b', 'c', 'd'], [1, 2, 3, 4]]
CombineAttributes(data)
data1 = [['a', 'b'], [1, 2], ['W', 'X']]
CombineAttributes(data1)
OUTPUT
Got the following AttributeList: [['a', 'b', 'c', 'd'], [1, 2, 3, 4]] its got 2 Attributes in it and im going to Combine Everything now
Im going to return the following after ive combined everything: [['a1', 'b1', 'c1', 'd1'], ['a2', 'b2', 'c2', 'd2'], ['a3', 'b3', 'c3', 'd3'], ['a4', 'b4', 'c4', 'd4']]
Got the following AttributeList: [['a', 'b'], [1, 2], ['W', 'X']] its got 3 Attributes in it and im going to Combine Everything now
Im going to return the following after ive combined everything: [['a1W', 'b1W'], ['a1X', 'b1X'], ['a2W', 'b2W'], ['a2X', 'b2X']]
答案2
得分: 1
以下是已经翻译好的内容:
这是使用itertools.product
和推导式的另一种答案,几乎给出了您所要求的完全相同的输出:
from pprint import pprint
from itertools import product
a = ['a', 'b', 'c', 'd']
b = ['1', '2', '3', '4']
axb = [
[''.join(_) for _ in list(product(a, b))][_:_ + len(a)]
for _ in range(0, len(a) * len(b), len(a))
]
pprint(axb)
结果如下:
[['a1', 'a2', 'a3', 'a4'],
['b1', 'b2', 'b3', 'b4'],
['c1', 'c2', 'c3', 'c4'],
['d1', 'd2', 'd3', 'd4']]
如您所见,您需要对axb
进行转置才能获得所需的精确输出。可以使用numpy.transpose()
来实现这一点,例如:
from numpy import transpose
transpose(axb)
或者,如果您想使用Python的标准模块,您可以使用以下方法对结果进行转置:
axbcopy = axb.copy()
for i in range(len(axb)):
for j in range(len(axb[0])):
axbcopy[i][j] = axb[j][i]
或者,使用更具Python风格的方法:
axbt = list(map(list, zip(*axb)))
其中,axbt
将保存最终的结果。
英文:
This is an alternative answer using itertools.product
and comprehensions, which gives you almost the exact output you asked:
from pprint import pprint
from itertools import product
a = ['a', 'b', 'c', 'd']
b = ['1', '2', '3', '4']
axb = [
[''.join(_) for _ in list(product(a, b))][_:_ + len(a)]
for _ in range(0, len(a) * len(b), len(a))
]
pprint(axb)
Resulting in:
[['a1', 'a2', 'a3', 'a4'],
['b1', 'b2', 'b3', 'b4'],
['c1', 'c2', 'c3', 'c4'],
['d1', 'd2', 'd3', 'd4']]
As you see, you will need to transpose axb
to get the exact output needed. That can be achieved with numpy.transpose()
, for example. Look:
>>> from numpy import transpose
>>> transpose(axb)
array([['a1', 'b1', 'c1', 'd1'],
['a2', 'b2', 'c2', 'd2'],
['a3', 'b3', 'c3', 'd3'],
['a4', 'b4', 'c4', 'd4']], dtype='<U2')
>>>
If you want to stick with Python's standard modules, you can transpose the result with:
axbcopy = axb.copy()
for i in range(len(axb)):
for j in range(len(axb[0])):
axbcopy[i][j] = axb[j][i]
Or, with a more Pythonic method:
axbt = list(map(list, zip(*axb)))
Where axbt
will hold the final result.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论