people = ["James","COP","George","COP","Sam","Mac","Johnny","Karina"]cops = [(idx+1) for idx, val in enumerate(people) if val == "COP"] #cops' positionspeoplePositions = [(x+1) for x in range(len(people))] #index positionsdistances = []for x in peoplePositions: for y in cops: distances.append(abs(x-y))#the output would be "Johnny" 大家好!我正在研究這個問題,基本上我有一個包含一些人/物體的列表,它實際上是一個圓桌,即它的頭部連接到它的尾部。現在我想獲取“COP”和人之間的(索引位置)距離,然后輸出與“COP”距離最大的人。如果它們都具有相同的距離,則輸出必須是它們全部。這是我的代碼,最后我得到了所有人和“COP”之間的距離。我考慮過用一系列 len(peoplePositions) 和一系列 len(cops) 進行距離的嵌套循環,但沒有任何進展。
1 回答

Cats萌萌
TA貢獻1805條經驗 獲得超9個贊
您需要計算每個人到每個 的最小距離COP。這可以計算為:
min((p - c) % l, (c - p) % l)
其中p是 person 的索引,c是 the 的索引COP以及l數組的長度。然后,您可以計算這些距離的最小值,以獲得從一個人到任何COPs 的最小距離。然后,您可以計算這些值的最大值,并people根據它們的距離等于最大值來過濾數組:
people = ["James","COP","George","COP","Sam","Mac","Johnny","Karina"]
cops = [idx for idx, val in enumerate(people) if val == "COP"]
l = len(people)
distances = [min(min((p - c) % l, (c - p) % l) for c in cops) for p in range(l)]
maxd = max(distances)
pmax = [p for i, p in enumerate(people) if distances[i] == maxd]
print(pmax)
輸出:
['Johnny']
添加回答
舉報
0/150
提交
取消