下午好,
如标题所示,我正在尝试转换一组在第一个位置具有重复值但在第二个位置具有不同值的元组。
我敢肯定有一个很简单的方法来构建这个List对象,但是我对这种语言还很陌生,我正在努力做到这一点。
我尝试制作字典,但发现字典需要唯一键,否则原始值将被覆盖。
转换的目的是按ID将这些记录发布到smartsheet api。我想遵循他们对批量处理的建议,即每n条记录仅对表一次ping一次,而不是对ping表n次。
任何建议将不胜感激!
谢谢,钱宁
我将分两个步骤进行。首先,创建一个字典,其中键是元组的第一个元素,值是共享相同第一个元素的所有第二个元素的列表。
其次,将键和值插入适当的列表中。
import itertools
# your initial set of tuples
tuples = {('Id', 'row1'), ('Id', 'row2'), ('Id2', 'row3')}
# create a dict, as above -
# key is the first element of tuple
# value is a list of the second elements of those tuples
dct = {}
for t in tuples:
dct.setdefault(t[0], []).append(t[1])
print(dct)
# {'Id2': ['row3'], 'Id': ['row1', 'row2']}
# coalesce the dict's keys and values into a list
# we use itertools.chain to make this more straightforward,
# but it's essentially concatenating the tuple elements of dct.items() to
# each other, by using the unpacking operator `*` to provide them individually
# as arguments.
outp = list(itertools.chain(*dct.items()))
print(outp)
# ['Id2', ['row3'], 'Id', ['row1', 'row2']]
这具有线性时间复杂度,因为它tuples
正好遍历输入()的每个元素两次。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句