我是Python的新手,为我的丑陋代码感到抱歉... 我需要创建一个程序,允许我使用另一个列表中的条件来重新排列列表。 我有一个包含名字的列表和一个包含姓氏的列表(排序很重要,因为每个名字都对应于eahc姓氏)。想法是创建一个从名字中随机抽取的新列表,条件是两个姓氏不能并排(并且姓氏的姓氏和名字必须不同)...不确定我是这里很清楚,希望您能通过查看我的代码来得到它。
这是我下面的代码(在删除while循环并手动重复时可以使用...)。我相信有一种方法可以非常简单地完成此操作...
有什么帮助吗?
梅尔
我的代码:
import random
first_names = ['an','bn','ji','au','jo','ki','ko','bo','mi','li']
last_names = ['A','A','A','R','R','R','C','C','C','C']
results =[]
results_names = []
#picking the first item
tirage = random.choice(list(enumerate(first_names)))
index = tirage[0]
pren = tirage[1]
results.append(pren)
results_names.append(last_names[index])
first_names.remove(pren)
last_names.pop(index)
while len(first_names) > 0 :
tirage = random.choice(list(enumerate(first_names)))
index = tirage[0]
pren = tirage[1]
if last_names[index] != results_names[len(last_names)-1]:
results.append(pren)
results_names.append(last_names[index])
first_names.remove(pren)
last_names.pop(index)
print(results)
print(results_names)
if len(resultats_noms) == 10:
print('liste completed')
if len(first_names)>9 and last_names[index] == results_names[len(results_names)-1]:
print('blocked, need to restart',len(results_names),'first names of 10')
答案 0 :(得分:0)
您可以使用random.shuffle()强行使用它:
import random
def neighbouring(l):
"""Returns True if any 2 elements in l have the same last name."""
return any( last == l[idx+1][1] for idx,(_,last) in enumerate(l[:-1]) )
first_names = ['an','bn','ji','au','jo','ki','ko','bo','mi','li']
last_names = ['A','A','A','R','R','R','C','C','C','C']
# combine first and last name to name-tuples
names = list(zip(first_names,last_names))
print(names)
tries = 0
len_names = len(names)
# brute force: shuffle until neighbouring(names) == False
while neighbouring(names) and tries < len_names*100: # abort after 100*listlenght tries
random.shuffle(names)
tries += 1
print(names)
输出:
# before
[('an', 'A'), ('bn', 'A'), ('ji', 'A'), ('au', 'R'), ('jo', 'R'),
('ki', 'R'), ('ko', 'C'), ('bo', 'C'), ('mi', 'C'), ('li', 'C')]
# after
[('bn', 'A'), ('jo', 'R'), ('mi', 'C'), ('au', 'R'), ('ko', 'C'),
('ji', 'A'), ('li', 'C'), ('an', 'A'), ('ki', 'R'), ('bo', 'C')]
要获取基本列表:
first_names, last_names = zip(*names)
print(list(first_names))
print(list(last_names))
输出:
['ko', 'bn', 'ki', 'an', 'bo', 'jo', 'mi', 'ji', 'li', 'au']
['C', 'A', 'R', 'A', 'C', 'R', 'C', 'A', 'C', 'R']
修复名称无法按期望组合的无尽运行:
tries = 0
max_tries = len(names) * 100
while neighbouring(names) and tries < max_tries:
random.shuffle(names)
tries += 1
if tries == max_tries:
print("Check the data - list might still have neighboring dupes after ",
tries, " shufflings")
else:
print("Used ",tries," out of ",max_tries," shufflings")
print(names)
first_names, last_names = zip(*names)
print(list(first_names))
print(list(last_names))