我有一个包含一些静态元素的列表:
['foo', 1, '', 0]
我有一个元组列表:
[('val1', 9), ('val2', 'val3'), ('val4', '')]
如何在元组列表的每个元组末尾添加列表元素?
输出
[
('val1', 9, 'foo', 1, '', 0),
('val2', 'val3', 'foo', 1, '', 0),
('val4', '', 'foo', 1, '', 0)
]
答案 0 :(得分:3)
只需使用添加的元组来重建元组列表:
elts = ['foo', 1, '', 0]
t = [('val1', 9), ('val2', 'val3'), ('val4', '')]
result = [e+tuple(elts) for e in t]
结果:
[('val1', 9, 'foo', 1, '', 0),
('val2', 'val3', 'foo', 1, '', 0),
('val4', '', 'foo', 1, '', 0)]
您可能希望将elts
设置为tuple
以避免循环中的转换:
elts = ['foo', 1, '', 0] # or elts = tuple(elts) if you have an existing list
result = [e+elts for e in t]
答案 1 :(得分:1)
在python中,元组是不可变的集合,这意味着您无法修改其中的元素。但是,您可以 将变量重新分配给新的元组,该元组可以像列表一样使用。
list1 = ['foo', 1, '', 0]
list2 = [('val1', 9), ('val2', 'val3'), ('val4', '')]
endlist = []
for x in range(len(list2)):
endlist += [tuple(list2[x]) + tuple(list1)]
答案 2 :(得分:0)
您可以为此使用元组拆包:
void increasingOrder(vector<int> &v)
{
vector<int>::iterator itMin = v.begin();
for (vector<int>::iterator itNew = v.begin(); itNew < v.end(); itNew++)
{
bool isSwitched = false;
for (vector<int>::iterator it = itNew; it < v.end(); it++)
{
if (*it < *itMin)
{
itMin = it;
isSwitched = true;
}
}
if (isSwitched)
{
int temp = *itNew;
*itNew = *itMin;
*itMin = temp;
}
}
}
int main() {
vector<int> v = { 3, 1, 2, 4 };
increasingOrder(v);
}
它给出了:
elts = ['foo', 1, '', 0]
t = [('val1', 9), ('val2', 'val3'), ('val4', '')]
result = [(*t_item, *elts) for t_item in t]
它比[('val1', 9, 'foo', 1, '', 0),
('val2', 'val3', 'foo', 1, '', 0),
('val4', '', 'foo', 1, '', 0)]
列表较大的https://stackoverflow.com/a/54409510/8056572快一点:
t