2013-06-21 36 views
2

我嘗試了像Lambda,List comprehension和其他的序列生成器,但似乎我無法得到我真正想要的東西。我的最終目標是從一個字符串打印字的序列,例如字符串[1:3]使用Number應用於字符串的序列生成

我在尋找:

a = [0,13,26,39] 
b = [12,25,38,51] 

str = 'If you are done with the file, move to the command area across from the file name in the RL screen and type' 

read = str.split() 

read[0:12] 
['If', 'you', 'are', 'done', 'with', 'the', 'file,', 'move', 'to', 'the', 'command', 'area'] 
read[13:25] 
['from', 'the', 'file', 'name', 'in', 'the', 'RL', 'screen', 'and', 'type'] 
+2

嘛,有什麼問題嗎? –

+0

如果我可能會問,在什麼情況下你會發現這樣的問題? – PyRulez

回答

5

使用zip

>>> a = [0,13,26,39] 
>>> b = [12,25,38,51] 
>>> strs = 'If you are done with the file, move to the command area across from the file name in the RL screen and type' 
>>> spl = strs.split() 
>>> for x,y in zip(a,b): 
...  print spl[x:y] 
...  
['If', 'you', 'are', 'done', 'with', 'the', 'file,', 'move', 'to', 'the', 'command', 'area'] 
['from', 'the', 'file', 'name', 'in', 'the', 'RL', 'screen', 'and', 'type'] 
[] 
[] 

zip回報元組列表,其中每個元組包含與傳遞給它的迭代中相同索引的項目:

>>> zip(a,b) 
[(0, 12), (13, 25), (26, 38), (39, 51)] 

如果您想要內存有效的解決方案,請使用itertools.izip,因爲它會返回一個迭代器。

您可以使用str.join,如果你想從切片列表中創建一個字符串:

for x,y in zip(a,b): 
    print " ".join(spl[x:y]) 
...  
If you are done with the file, move to the command area 
from the file name in the RL screen and type 

更新:創建ab

>>> n = 5 
>>> a = range(0, 13*n, 13) 
>>> b = [ x + 12 for x in a] 
>>> a 
[0, 13, 26, 39, 52] 
>>> b 
[12, 25, 38, 51, 64] 
+0

我該如何創建列表a和b。這些是在a和b的情況下N + 1數字多於13的序列。另外b [0] = a [0] + 12 – LonelySoul

+0

@LonelySoul查看我的更新。 –

+0

精彩..非常感謝你 – LonelySoul

1

你提到的λ,所以:

f = lambda s, i, j: s.split()[i:j] 
>>> f("hello world how are you",0,2) 
['hello', 'world'] 

好像你在做兩個列表中的切片索引,我可以建議一個字典或元組列表嗎?

str = 'If you are done with the file, move to the command area across from the file name in the RL screen and type' 
slices = [(0, 13), (12, 25)] 
dslices = {0:13, 12:25} 
for pair in slices: 
    print f(str, pair[0], pair[1]) 
for key in dslices: 
    print f(str, key, dislikes[key]) 

我不喜歡使用zip,當你有選擇只是格式化你的數據更好。

2
a = [0,13,26,39] 
b = [12,25,38,51] 
str = 'If you are done with the file, move to the command area across from the file name in the RL screen and type' 

read = str.split() 
extra_lists = [read[start:end] for start,end in zip(a,b)] 
print extra_lists 
3

你的意思是:

>>> [read[i:j] for i, j in zip(a,b)] 
[['If', 'you', 'are', 'done', 'with', 'the', 'file,', 'move', 'to', 'the', 
'command', 'area'], ['from', 'the', 'file', 'name', 'in', 'the', 'RL', 
'screen', 'and', 'type'], [], []] 

>>> ' '.join[read[i:j] for i, j in zip(a,b)][0]) 
'If you are done with the file, move to the command area' 

>>> ' '.join[read[i:j] for i, j in zip(a,b)][1]) 
'from the file name in the RL screen and type' 
+0

感謝@dansalmo的幫助。它對我來說是新的。 – LonelySoul