我有一个看起来像下面的列表
[('Jon', '177'), ('Danei', '1420'), ('Adan', '146'), ('Gabriel', '110'), ('Chase', '117'), ('Hetmyer', '418'), ('Smith', '162')]
这实际上是一个自定义排序列表,我想通过固定列表中的第一个元素来更改其顺序,即如果我将Hetmyer
作为输入,新列表应该是这样
[('Hetmyer', '418'), ('Smith', '162'),('Jon', '177'), ('Danei', '1420'), ('Adan', '146'), ('Gabriel', '110'), ('Chase', '117')]
如果我将Adan作为输入,新列表应如下所示
[('Adan', '146'), ('Gabriel', '110'), ('Chase', '117'), ('Hetmyer', '418'), ('Smith', '162'),('Jon', '177'), ('Danei', '1420') ]
基本上,我给出的任何输入都应成为列表的第一个成员,而其余顺序应保持原样,即它应从输入开始,并在输入成员之前以列表成员结束,我们有任何内置函数吗
答案 0 :(得分:2)
找到位置
for i, item in enumerate(l):
if item[0] == "Hetmyer":
pos = i
建立新列表:
m = l[pos:] + l[:pos]
结果:
[('Hetmyer', '418'), ('Smith', '162'), ('Jon', '177'), ('Danei', '1420'), ('Adan', '146'), ('Gabriel', '110'), ('Chase', '117')]
答案 1 :(得分:2)
s = input()
a = [('Jon', '177'), ('Danei', '1420'), ('Adan', '146'), ('Gabriel', '110'), ('Chase', '117'), ('Hetmyer', '418'), ('Smith', '162')]
for i in a:
if i[0] == s:
a = a[a.index(i):] + a[:a.index(i)]
print(a) #[('Adan', '146'), ('Gabriel', '110'), ('Chase', '117'), ('Hetmyer', '418'), ('Smith', '162'), ('Jon', '177'), ('Danei', '1420')]
答案 2 :(得分:0)
def resort(name_list, name):
"""Return the given name_list ordered using the given name."""
index = list(zip(*name_list))[0].index(name)
return name_list[:index] + name_list[index:]
resort(names, "Danei")
结果:
[('Jon', '177'),
('Danei', '1420'),
('Adan', '146'),
('Gabriel', '110'),
('Chase', '117'),
('Hetmyer', '418'),
('Smith', '162')]