2016-12-14 60 views
-1

我正在使用Python 2.6,並希望通過'keyN'生成'key1'的最有效方法?我曾嘗試沒有成功:什麼是生成包含'key1'到'keyN'的列表的最有效方法?

Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> N=10 
>>> x = range(1, N + 1) 
>>> 'key' + str(x) 
'key[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]' 
>>> map('key' + _, map(str, range(N + 1))) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: 'str' object is not callable 
>>> map('key' + ?, map(str, range(N + 1))) 
    File "<stdin>", line 1 
    map('key' + ?, map(str, range(N + 1))) 
       ^
SyntaxError: invalid syntax 
>>> map('key' + *, map(str, range(N + 1))) 
    File "<stdin>", line 1 
    map('key' + *, map(str, range(N + 1))) 
       ^
SyntaxError: invalid syntax 
>>> 
+0

我認爲這個問題不值得讚賞。這是一個有效的問題,它包括一系列已經嘗試過的方法。由於他們不工作,OP正在尋求解決方案。爲什麼downvote呢? –

回答

2

如果你想有一個清單作爲輸出,你可以簡單地這樣做:

>>> N = 10 
>>> ['key' + str(i) for i in range (0, N)] 
['key0', 'key1', 'key2', 'key3', 'key4', 'key5', 'key6', 'key7', 'key8', 'key9'] 

如果你想使用map提供拉姆達是這樣的:

map(lambda x: 'key' + str(x), range(0, 10)) 

但是,正如您從答案中可以看到的那樣,還有其他(或許更乾淨)的方法。

1

你可以嘗試

['key%s' % x for x in range(N)] 
2

我會說一個列表理解是最簡潔:

lst = ['key{}'.format(i) for i in range(N)] 

而且你也不需要用range

指定零開始索引
相關問題