python小技巧

1

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

'''
设想的结果
[1]
[2]
[3]
打印结果
[1]
[1, 2]
[1, 2, 3]
'''

#改成这样
def f(a, L=None):
    if L==None:
        L=[]
    L.append(a)
    return L


print(f(1))
print(f(2))
print(f(3))

 

2 for循环的else,以及和break,continue之间的区别

  其实还是break,continue本来的意思,

 

 

for n in range(2,10):
    for i in range(2,n):
        if n%i ==0:
            print(n, ' equals ', i ,'*',n/i)
            break
    else:
        print(n, ' is prime number')
else:
    print('else in for loop 1')

'''
输出结果
2  is prime number
3  is prime number
4  equals  2 * 2.0
5  is prime number
6  equals  2 * 3.0
7  is prime number
8  equals  2 * 4.0
9  equals  3 * 3.0
else in for loop 1
'''
        
for n in range(2,10):
    if n%2==0:
        print(n,' is an even number')
        continue
    print(n, ' is an odd number')
else:
    print('else in for loop 2')

'''
输出结果
2  is an even number
3  is an odd number
4  is an even number
5  is an odd number
6  is an even number
7  is an odd number
8  is an even number
9  is an odd number
else in for loop 2

'''

  

 3 切片可以越界

list=[1,2,3,4,5,6,7,8]
print(list[10])#越界错误

print(list[4:10])#[5, 6, 7, 8]

 

 

 

List Comprehensions两个循环

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y

[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] 

 

 

 

 

 

5.6. Looping Techniques

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.

>>>
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

>>>
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

>>>
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

>>>
>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

>>>
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear

To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

>>>
>>> words = ['cat', 'window', 'defenestrate']
>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

 

以 list 中 tuple 的第二个值排序

list = [(1, 2, 3), (2, 1, 3), (3, 2, 1), (3, 4, 5)]

sorted_list = sorted(list, key = lambda list : list[1])

output:

sorted_list = [(2, 1, 3), (1, 2, 3), (3, 2, 1), (3, 4, 5)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值