我有两个列表
ATFIM_Table_Field=['City', 'City', 'Category', 'City', 'Category', 'Category']
ATFIM_Table_Values=['chennai', 'erode', 'printer', 'nagpur', 'pc', 'notebook']
我想在Field中找到重复项,并在重复Field的索引处合并Values的元素。
预期输出-["'printer','pc','notebook'","'chennai','erode','nagpur'"]
这是我尝试的代码:
if len(ATFIM_Table_Field) != len(set(ATFIM_Table_Field)):
newlist=[]
newelement=[]
def duplicates(lst, item):
return [i for i, x in enumerate(lst) if x == item]
dup=dict((x, duplicates(ATFIM_Table_Field, x)) for x in set(ATFIM_Table_Field) if ATFIM_Table_Field.count(x) > 1)
duplen=len(dup)
for i in range(duplen):
mergevalueindex=list(dup.values())
for j in range(0,duplen):
mergevalueindex2=mergevalueindex[j]
for e in mergevalueindex2:
newlist.append(ATFIM_Table_Values[e])
d="','"
newelement.append("'"+d.join(newlist)+"'")
这是我得到的输出:
["'printer'",
"'printer','pc'",
"'printer','pc','notebook'",
"'printer','pc','notebook','chennai'",
"'printer','pc','notebook','chennai','erode'",
"'printer','pc','notebook','chennai','erode','nagpur'"]
答案 0 :(得分:0)
您想要的并不清楚。我明白了试试这个:
unique_field2indeces = {}
for index in range(len(Field)):
if Field[index] in list(unique_field2indeces.keys()):
unique_field2indeces[Field[index]].append(index)
else:
unique_field2indeces[Field[index]] = [index]
associated_values = []
for index_list in unique_field2indeces.values():
value_list = [Values[index] for index in index_list]
associated_values.append(value_list)
答案 1 :(得分:0)
如果您显示了确切的预期输出,那么这是代码:
Field=['City', 'City', 'Category', 'City', 'Category', 'Category']
Values=['chennai', 'erode', 'printer', 'nagpur', 'pc', 'notebook']
unique_fields = set(Field)
merged_list = []
for field in unique_fields:
templist = []
for i,f in enumerate(Field):
if f == field:
templist.append(Values[i])
merged_list.append(str(templist).strip('[\]'))
print(merged_list)
输出:
["'printer', 'pc', 'notebook'", "'chennai', 'erode', 'nagpur'"]