添加列表python的特定元素

时间:2015-05-31 11:54:41

标签: python list

“pyschool”练习:

  

“定义一个函数调用addFirstAndLast(x),它接收一个数字列表并返回第一个和最后一个数字的总和。”

这是我提出的最佳解决方案。是否有一种更优雅的方式来编写这个只使用内置函数的函数?

def addFirstAndLast(x):
    sum_list = []
    if len(x) == 0:
        return 0
    elif len(x) == 1 :
        return int(x[0])
    elif len(x) > 1 :
        sum_list.append(x[0]) 
        sum_list.append(x[-1])
    return sum(sum_list)

4 个答案:

答案 0 :(得分:2)

>>> def addFirstAndLast(x):
...   return (x[0]+x[-1])/(1/len(x)+1) if x else 0
... 
>>> addFirstAndLast([])
0
>>> addFirstAndLast([1])
1
>>> addFirstAndLast([1,3])
4

注1 :只有当列表的长度为1时,(1/len(x)+1)的结果才是2,所以你将第一个和最后一个元素的总和除以2,否则除以1。 / p>

注2 :如果您在python 3中,请使用//代替/

答案 1 :(得分:2)

Kasra的答案要好得多,但这是一种稍微不同的方式。由于NSMutableAttributedString *mutableAttString = [[NSMutableAttributedString alloc] init]; NSTextAttachment *attachment = [[NSTextAttachment alloc] init]; attachment.image = [UIImage imageNamed:@"a.png"]; NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment]; [mutableAttString replaceCharactersInRange:getanswer withAttributedString:attachmentString]; 总是存在,因此您只需检查是否应添加x[0]

x[-1]

答案 2 :(得分:0)

def addFirstAndLast(x):
    if x:
        return sum(zip(*filter(lambda (i,s): i == 0 or i == len(x) - 1, enumerate(x)))[1])
    else:
        return 0

枚举列表中的元素,过滤,解压缩然后返回总和。

答案 3 :(得分:0)

使用扩展切片表示法,max处理空列表。

for i in range(5):
    a = range(10, 10 + i)
    b = a[::max(1, len(a)-1)]
    print a, b, sum(b)

<强>输出

[] [] 0
[10] [10] 10
[10, 11] [10, 11] 21
[10, 11, 12] [10, 12] 22
[10, 11, 12, 13] [10, 13] 23

这是一个在函数中执行此操作的版本。

def add_first_and_last(x):
    return sum(x[::max(1, len(x)-1)])

for i in range(5):
    a = range(10, 10 + i)
    print a, add_first_and_last(a)

<强>输出

[] 0
[10] 10
[10, 11] 21
[10, 11, 12] 22
[10, 11, 12, 13] 23

在Kasra的提示下,我已经对现有的主要答案进行了一些时间测试。我还添加了Peter的算法的修改版本,其中稍微更快。

from timeit import Timer

def addFirstAndLast_Sam(x):
    sum_list = []
    if len(x) == 0:
        return 0
    elif len(x) == 1 :
        return int(x[0])
    elif len(x) > 1 :
        sum_list.append(x[0]) 
        sum_list.append(x[-1])
    return sum(sum_list)

def add_first_and_last_PM2Ring_slow(x):
    return sum(x[::max(1, len(x)-1)])

def add_first_and_last_PM2Ring_fast(x):
    return x[0] + x[-1] if len(x) > 1 else x[0] if x else 0

def firstAndLast_Peter(x):
    if x:
        value = x[0]
        if len(x)>1:
            value += x[-1]
        return value
    return 0

def addFirstAndLast_Kasra(x):
    return (x[0] + x[-1]) // (1 // len(x) + 1) if x else 0

funcs = (
    add_first_and_last_PM2Ring_fast,
    firstAndLast_Peter,
    addFirstAndLast_Kasra,
    add_first_and_last_PM2Ring_slow,
    addFirstAndLast_Sam,
)

num = 10
lists = [range(10, 10 + i) for i in range(num + 1)]

def verify():
    ''' Verify that the functions actually perform as intended '''
    print 'Verifying...'
    for func in funcs:
        fname = func.func_name
        print '\n%s' % fname
        for a in lists:
            print a, func(a)

def time_test(loops, reps):
    ''' Print timing stats for all the functions '''
    print '\nTiming tests\nLoops = %d, Repetitions = %d' % (loops, reps)

    for func in funcs:
        fname = func.func_name
        print '\n%s' % fname
        setup = 'from __main__ import lists, %s' % fname
        t = Timer('[%s(a) for a in lists]' % fname, setup)
        r = t.repeat(reps, loops)
        r.sort()
        print r

verify()
time_test(loops=10000, reps=3)

<强>输出

Verifying...

add_first_and_last_PM2Ring_fast
[] 0
[10] 10
[10, 11] 21
[10, 11, 12] 22
[10, 11, 12, 13] 23
[10, 11, 12, 13, 14] 24
[10, 11, 12, 13, 14, 15] 25
[10, 11, 12, 13, 14, 15, 16] 26
[10, 11, 12, 13, 14, 15, 16, 17] 27
[10, 11, 12, 13, 14, 15, 16, 17, 18] 28
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 29

firstAndLast_Peter
[] 0
[10] 10
[10, 11] 21
[10, 11, 12] 22
[10, 11, 12, 13] 23
[10, 11, 12, 13, 14] 24
[10, 11, 12, 13, 14, 15] 25
[10, 11, 12, 13, 14, 15, 16] 26
[10, 11, 12, 13, 14, 15, 16, 17] 27
[10, 11, 12, 13, 14, 15, 16, 17, 18] 28
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 29

addFirstAndLast_Kasra
[] 0
[10] 10
[10, 11] 21
[10, 11, 12] 22
[10, 11, 12, 13] 23
[10, 11, 12, 13, 14] 24
[10, 11, 12, 13, 14, 15] 25
[10, 11, 12, 13, 14, 15, 16] 26
[10, 11, 12, 13, 14, 15, 16, 17] 27
[10, 11, 12, 13, 14, 15, 16, 17, 18] 28
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 29

add_first_and_last_PM2Ring_slow
[] 0
[10] 10
[10, 11] 21
[10, 11, 12] 22
[10, 11, 12, 13] 23
[10, 11, 12, 13, 14] 24
[10, 11, 12, 13, 14, 15] 25
[10, 11, 12, 13, 14, 15, 16] 26
[10, 11, 12, 13, 14, 15, 16, 17] 27
[10, 11, 12, 13, 14, 15, 16, 17, 18] 28
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 29

addFirstAndLast_Sam
[] 0
[10] 10
[10, 11] 21
[10, 11, 12] 22
[10, 11, 12, 13] 23
[10, 11, 12, 13, 14] 24
[10, 11, 12, 13, 14, 15] 25
[10, 11, 12, 13, 14, 15, 16] 26
[10, 11, 12, 13, 14, 15, 16, 17] 27
[10, 11, 12, 13, 14, 15, 16, 17, 18] 28
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 29

Timing tests
Loops = 10000, Repetitions = 3

add_first_and_last_PM2Ring_fast
[0.15383195877075195, 0.15486502647399902, 0.18578314781188965]

firstAndLast_Peter
[0.16625690460205078, 0.16726803779602051, 0.17240190505981445]

addFirstAndLast_Kasra
[0.19242000579833984, 0.19251012802124023, 0.21216797828674316]

add_first_and_last_PM2Ring_slow
[0.38388991355895996, 0.39070892333984375, 0.39607501029968262]

addFirstAndLast_Sam
[0.38914084434509277, 0.38966894149780273, 0.41235685348510742]

正如您所看到的,我的原始代码肯定不是最快,但 最短。 :)