2012-12-23 56 views
0

是否有簡單的方法將指標函數應用於列表?即我有一個包含一些數字的列表,並且我想返回另一個相同大小的列表,例如,正數在原始列表中的那些列表和負數在原始列表中的零。將指標函數應用於列表

+2

[這可能是值得的手錶。(http://www.youtube.com /手錶?ν= pShL9DCSIUw) –

回答

9

只需用一個列表理解:

>>> orig = [-3, 2, 5, -6, 8, -2] 
>>> indic = [1 if x>0 else 0 for x in orig] 
>>> indic 
[0, 1, 1, 0, 1, 0] 
1

要生成例子的結果來看,我可能會做

cmp_list=map(cmp, your_list) 
one_zero_list=[] 
for item in cmp_list: 
    if item < 0: 
     one_zero_list.append(0) 
    elif item==0: 
     one_zero_list.append(0) #you didnt actually say what to do with 0 
    else: 
     one_zero_list.append(1)