2017-06-27 156 views
0

我正在研究一個python項目,我想在某種模式下訂購熊貓數據框的標題。 我的結果列表看起來如下:部分排序列表Python

Match1 attribute1 attribute2 attribute3 ... attributeN Score1 Match2 attributeM Score2 ... Match3 Score3 

我想訂購列表中的元素按以下模式

Match1 Score1 Match2 Score2 Match3 Score3 attribute1 attribute2 attributeN ... 

我知道有多少對比賽的/分數有列表。但我不知道會有多少屬性(我不需要訂購它們)。這些都是由特定的數據結構決定的。有沒有辦法讓我重新排列這樣一個列表的順序?

謝謝!

非常感謝您的幫助!

回答

1

使用sorted,您可以指定如下的鍵;第一個關鍵排序數在字符串末尾屬性列到最後,第二個鍵排序結果:

# cols = df.columns 
cols = ['Match1', 'attribute1', 'attribute2', 'attribute3', 'attributeN', 'Score1', 'Match2', 'attributeM', 'Score2', 'Match3', 'Score3'] 

import re 
sorted(cols, key=lambda x: (not bool(re.match('match|score', x, flags=re.I)), re.sub(r'.*(\d+)$', r'\1', x))) 

#['Match1', 
# 'Score1', 
# 'Match2', 
# 'Score2', 
# 'Match3', 
# 'Score3', 
# 'attribute1', 
# 'attribute2', 
# 'attribute3', 
# 'attributeM', 
# 'attributeN'] 
+0

感謝即時回覆。但是,這些屬性不是這種結構。他們有各種各樣的名字。是否還有辦法通過修改方法來完成它? – macintosh81

+0

你可以通過其他方式使關鍵;如果你確定比賽和比分列以比賽和比分開始,那麼你可以檢查他們並取消布爾值,它應該給你類似的結果。 – Psidom

+0

這工作得很好!感謝您的優雅解決方案。 – macintosh81

1

這裏是一些不完整的代碼開始與

index = 0 
for i in range(num_matches_and_scores]: 
    match1 = ??? # First instance of whatever you are trying to find 
    list1.remove(match1) 
    list1.insert(index, match1) 
    index += 1 
    score1 = ??? 
    list1.remove(score1) 
    list1.inset(index, score1) 
    index += 1 
+0

我明白了,讓我試着去實現它。謝謝! – macintosh81

+0

如果這是最有用的答案,如果您將其標記爲已接受,我將不勝感激。 :) –