`

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)]

分享到:
评论

相关推荐

    Python 小技巧.md

    Python 小技巧集锦是一个旨在帮助 Python 开发者提高编程效率和代码质量的资源。该资源汇总了一系列简洁、实用的 Python 编程技巧和技巧,涵盖了各种常见场景下的用例和解决方案。通过这些技巧,开发者可以更加高效...

    python小技巧.doc

    ### Python 编程小技巧详解 #### 一、列表推导式(List Comprehensions) 列表推导式是一种非常高效的方法,用于快速构建新的列表。它不仅简化了代码,还提高了可读性。列表推导式的语法如下: ```python new_list ...

    python使用小技巧

    下面是六个Python小技巧,涵盖了字符串格式化、标题化、列表推导式、字符串合并、统计列表元素个数和合并字典等多方面的内容。 1. Python3.6以后版本格式化字符串的新方法 在Python3.6以后版本中,引入了新的字符...

    10个Python小技巧你值得拥有

    以下是10个Python小技巧的详细解释: 1. **列表推导式**:列表推导式是Python中一种创建新列表的快捷方式。例如,要将列表`bag`中的所有元素翻倍,通常初学者可能会使用for循环,但列表推导式可以更简洁地实现这一...

    Python小技巧之列表推导式到匿名函数

    【Python小技巧之列表推导式到匿名函数】 在Python编程中,列表推导式(List Comprehension)和匿名函数(Lambda Function)是两个强大的工具,它们在编写简洁、高效的代码方面起着至关重要的作用。本文将深入探讨...

    Python学习教程,16个Python新技巧,让你进入变成新境界

    在本文中,我们将探索一些鲜为人知却非常好用的 Python 小技巧。学习和实现这些技巧,可以帮你节省编码的时间和精力,让代码更加优雅、高效。 现在就让我们深入探寻 Python 语言的这些隐藏宝藏吧! 1. 三元运算符 ...

    python小技巧:使用HTMLTestReport模板生成html报告

    总结一下,这个Python小技巧展示了如何使用`HTMLTestReport`库将自动化测试的结果生成HTML报告。通过这种方式,我们可以得到包含详细信息的测试报告,如测试用例的名称、状态、执行时间等,极大地提升了测试结果的...

    python小程序8 python小程序8 python小程序8 python小程序8

    在"Python小程序8"中,我们可能会接触到如文件操作、数据处理、网络通信等各种实用的编程技巧。 在描述中提到的"python小程序8"多次重复,暗示这个主题可能深入讲解了Python编程中的某个特定方面,比如可能是关于...

    3分钟学会一个Python小技巧

    ### Python时间日期转换小技巧详解 #### 引言 在Python开发过程中,处理时间与日期相关的数据是一项常见的任务。无论是数据库操作、文件命名还是日志记录等场景,开发者都需要频繁地进行时间日期的格式转换。...

    python小程序5 python小程序5 python小程序5 python小程序5

    "Python小程序5"可能是指一系列基于Python编写的、具有特定功能的小应用程序。这些小程序可能涵盖各种领域,如数据分析、网络爬虫、图形用户界面(GUI)工具、自动化任务等。描述中的重复表明这些小程序可能是系列的...

    常用的10个Python实用小技巧

    Python是一种强大且灵活的编程语言,它以其简洁的语法和...掌握这些Python小技巧,能够让你的编程更加高效和优雅。在日常工作中灵活运用,可以显著提升代码质量和开发效率。记得持续学习和实践,以深化对Python的理解。

    使用Python解决Windows文件名非用反斜杠问题(python 小技巧)

    要想让你的 Python 代码同时在 Windows 和 Mac/Linux 上工作,你需要处理不同系统文件名用不同斜杠的问题。而 Python 3 有一个名为「pathlib」的新模块,可以帮你解决这个麻烦,需要的朋友可以参考下

    python小程序7 python小程序7 python小程序7 python小程序7

    描述部分虽然重复了同样的话语,但我们可以推测其可能强调的是Python小程序的学习和实践,可能涵盖了一系列从小白到进阶的Python编程技巧和应用实例。在Python编程中,小程序通常涉及基础语法、数据结构、函数、模块...

    Python 小技巧 | Windows 文件名非用反斜杠

    在编程过程中,我们往往会遇到一个小麻烦——微软 Windows 系统在文件夹名之间使用反斜杠字符,而几乎所有其它的计算机(操作系统)都使用正斜杠: 这是由于上世纪 80 年代早期计算机历史上的一个小意外。「MS-...

    python小技巧总结

    1. list(列表)数据列拆分成多行的方法 现在有这样的一个dataframe df = pd.DataFrame({"A": [1,2,3,4], "B": [[1,2,3], ["a", "b"], [2,4,6], ["aaa", 00]]}) print(df) Out[8]: A B 0 1 [1, 2, 3] ...

    python一些不为人知的小技巧

    Python具有丰富和强大的库。它常被昵称为胶水语言,能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。常见的一种应用情形是,使用Python快速生成程序的原型(有时甚至是程序的最终界面),然后对...

    Python快速教程-Vamei-pdf版

    - **Python小技巧**:分享一些提高编程效率的小技巧,如列表推导式、生成器表达式等。 - **Python内置函数清单**:列出Python中所有内置函数及其用途。 - **Python简史**:回顾Python语言的发展历程,了解其设计理念...

Global site tag (gtag.js) - Google Analytics