2017-04-12 52 views
3

我想通過使用list-comprehentions在單行中編寫一個4-5行代碼。但這裏的問題是,我不能使用插入功能,所以即時通訊想知道是否有解決這個問題的方法?python插入函數列表comprehentions

原始代碼:

def order(text): 
    text = text.split() 
    for x in text: 
     for y in x: 
      if y in ('1','2','3','4','5','6','7','8','9'): 
       final.insert(int(y)-1, x) 

    return final 

是我迄今爲止嘗試:

return [insert(int(y)-1, x) for x in text.split() for y in x if y in ('1','2','3','4','5','6','7','8','9')] 

但我已經遇到了以下錯誤:
NameError:全局名稱 '插入' 沒有定義

我試圖使用insert因爲任務是使用每個單詞中顯示的數字重新排列列表中的項目。

,比如我有is2 Th1is T4est 3a作爲輸入,它應該站出來爲:
Th1is is2 3a T4est

+3

沒有插入功能。 'final.insert'是一個*方法*,並且不顯示實際是什麼'final'(大概是一個列表)。還要注意,你不應該使用列表解析的副作用 - 'list.insert'返回'None',我懷疑你想要的列表。 – jonrsharpe

+1

1.什麼是'final'? 2.列舉解釋_build list-on-the-fly_,所以你現在正在考慮將字段插入_nowhere_,因爲還沒有創建列表。 3.是的,沒有標準函數稱爲「插入」,爲什麼你期望它存在呢? – ForceBru

+0

@ForceBru Final是我在原始代碼中使用的列表。有沒有辦法爲這種列表理解運行該表達式?像「自插入」 –

回答

4

而不是使用列表理解的,你應該只sort在關鍵函數中使用這些號碼列表,例如使用正則表達式提取數字。

>>> import re 
>>> s = "is2 Th1is T4est 3a" 
>>> p = re.compile("\d+") 
>>> sorted(s.split(), key=lambda x: int(p.search(x).group())) 
['Th1is', 'is2', '3a', 'T4est'] 
+0

西部最快的槍!愚蠢的我,我仍然在爲你寫一個完全相同的代碼的解釋。做得好! –

+1

你也可以使用'int(filter(str.isdigit,x))'而不是正則表達式。如果你想支持Python 3,你必須使用'''.join()'。 – Blender

1

您可以通過拆分代碼成幾個簡單的功能實現您最初的想法,並作出適當的大小(充滿None S)的列表來保存的話,最終的排序:

def extract_number(text): 
    return int(''.join(c for c in text if c.isdigit())) 

def order(text): 
    words = text.split() 
    result = [None] * len(words) 

    for word in words: 
     result[extract_number(word) - 1] = word 

    return ' '.join(result) 

您也可以使用sorted()做到這一點的一條線:

def extract_number(text): 
    return int(''.join(c for c in text if c.isdigit())) 

def order(text): 
    return ' '.join(sorted(text.split(), key=extract_number))