Python Iteration Category

主要是做个笔记,以后可以方便梳理一下,尊重版权,特此申明下面信息均来自公司培训课PPT Nagiza F. Samatova, NC State Univ. All rights reserved

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

a_list = [1, '4', 9, 'a', 0, 4] 
squared_ints = [pow(e,2) for e in a_list if type(e) == int]
print(squared_ints) # output:[1, 81, 0, 16]
names=['Bob', 'JOHN', 'alice', 'bob', 'ALICE', 'J', 'BOB'] 
{
    
    name.title() for name in names if len(name) > 1}
#output: {
    
    'Alice', 'Bob', 'John'}

Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。default – 如果指定键的值不存在时,返回该默认值。

dict.get(key, default=None)

d = {
    
    'a':10, 'b': 34, 'A': 7, 'Z':3}
mcase_frequency = {
    
     k.lower() : d.get(k.lower(), 0) + d.get(k.upper(), 0) for k  in d.keys() }
print(mcase_frequency)
#output: 
{
    
    'a': 17, 'b': 34, 'z': 3}

While–loops

input_str = ' ' 
while input_str != 'Quit' and input_str != 'Exit': 
    input_str = input('Enter your name or type Quit or Exit:\n') 
    input_str = input_str.title() 
    print ('\tYou entered: ' + input_str) 
#output:
Enter your name or type Quit or Exit:
hello
	You entered: Hello
Enter your name or type Quit or Exit:
Quit
	You entered: Quit

else Clauses in the Loops
Any code in else block will execute if the loop did not hit a break statement
Useful when we are performing a search but no acceptable value was found and we need to raise an informative error

扫描二维码关注公众号,回复: 12718884 查看本文章
number_set = set (range(1, 6)) 
print ('\n\tSet of numbers: ' + str(number_set))
positive_flag = True 
for num in number_set: 
    if num < 0: 
        print ('\tFound a negative number: {}'.format(num)) 
        break 
else: 
    print ( '\tNumber is still positive...') 
    positive_flag = False   
#output:
Set of numbers: {
    
    1, 2, 3, 4, 5}
Number is still positive...

猜你喜欢

转载自blog.csdn.net/wumingxiaoyao/article/details/108931976
今日推荐