7. How to make Python code morePythonic:
1. Variable Exchange:
A, B = B, a
2 . Set traversal with index position:
colors = ['red'Green'blue ' ' Yellow ' ] for in Enumerate (colors):print'---> ', color
3. String Connection:
names = ['Raymond','Rachel','Matthew','Roger','Betty','Melissa','Judith','Charlie']Print ', '. Join (names)
Note: When using the + operation, a new string object is generated in memory each time, and the Join method produces only one string object.
4. Open/Close files:
With open ('data.txt'= F.read ()
Note: With the WITH statement, the file object is closed automatically after the file operation is performed.
5. Rational use of the list
fromCollectionsImportDequenames= Deque (['Raymond','Rachel','Matthew','Roger','Betty','Melissa','Judith','Charlie']) names.popleft ()#Delete the leftmost elementNames.appendleft ('Mark')#add a new element on the far left
Note: The list of lists is a data structure that is more efficient than the update operation, and is inefficient when deleting and inserting new elements, and queue deque is a two-way queue data structure that removes elements and inserts elements quickly
6. Sequence Unpacking:
' Vttalk ' ' female ' ' [email protected] ' = P
7 . Traverse the dictionary key and value
for inch D.iteritems (): Note: Iteritems returns an Iterator object, only the items method in Python3, equivalent to Iteritems Print ' ---> ', V
8. Chain comparison operation: If < Age < 60:
Guess:>>> false = = False = = True (The answer is: false)
9,if/else three mesh operation:
' male ' if ' male ' Else ' female '
10, truth value judgment:
if If attr = = True:if not if# Determines if the list is empty
11.For/else Statement
For else is a specific syntax format in Python, and the code in else executes after the for loop has traversed all elements
12. Get dictionary elements
D = {'name''foo'}d.get ("name " " Unknow " # if D has key=name, it gets its value, otherwise key=unknow
13. Preset Dictionary default value
(Scenario: When you are grouping by key, you have to check that the key is already in the dictionary every time.) )
Groups = {} for in # mode one, commonly used
14. Dictionary derivation style
numbers = [1, 2, 3forif number > 1}print# {2:4, 3:6}
15,...
Python Note 7: Elegant python