假设您有一个元组列表,例如:
list1 = [(0, 0, 0), (1, 0, 0), (2, 0, 0), (3, 0, 0)]
并且您希望将元组(0,1,0)添加到它应该按顺序排列的列表中:
list1 = [(0, 0, 0), (0,1,0), (1, 0, 0), (2, 0, 0), (3, 0, 0)]
并说你还想将元组(0,1,1)添加到它应该按顺序排列的列表中:
list1 = [(0, 0, 0), (0,1,0), (0,1,1), (1, 0, 0), (2, 0, 0), (3, 0, 0)]
并且说你还想将元组(3,1,0)添加到它应该按顺序排列的列表中:
list1 = [(0, 0, 0), (0,1,0), (0,1,1), (1, 0, 0), (2, 0, 0), (3, 0, 0), (3, 1, 0)]
我想尝试提出一个函数,该函数根据元组中的值(def(value1,value2,value3):...)获取三个参数,然后使用它可以找到索引值并插入列表中的元组以正确的顺序排列。发现它非常困难和帮助将不胜感激
答案 0 :(得分:2)
如果list1
已排序,则插入单个元组:
import bisect
bisect.insort(list1, (0, 1, 0))
合并两个排序列表:
import heapq
tuples = [(0,1,0), (0,1,1), (3,1,1)]
list1 = list(heapq.merge(list1, tuples))
或小名单(len(L) < 1000000
):
list1.extend(tuples)
list1.sort()
答案 1 :(得分:1)
为了简单起见,只需附加新值并对列表进行排序:
a = [(0, 0, 0), (1, 0, 0), (2, 0, 0), (3, 0, 0)]
def add_to_list(item1, item2, item3, the_list):
the_list.append((item1, item2, item3))
return sorted(the_list)
print(add_to_list(0, 1, 0, a))
答案 2 :(得分:0)
>>> def fun(value1, value2, value3):
tup = (value1, value2, value3)
list1.append(tup)
list1.sort()
return(list1)
>>> list1 = [(0, 0, 0), (0,1,0), (1, 0, 0), (2, 0, 0), (3, 0, 0)]
>>> fun(0,1,1)
[(0, 0, 0), (0, 1, 0), (0, 1, 1), (1, 0, 0), (2, 0, 0), (3, 0, 0)]
答案 3 :(得分:0)
没有写作功能:
a = [(0, 0, 0), (1, 0, 0), (2, 0, 0), (3, 0, 0)]
a = sorted(a+[(0,1,1)])
使用函数(t是元组):
f = lambda a,t: sorted(a+[t])
a = f(a, (1, 1, 0))