Today I will summarize some of the commonly used style codes in python. These may be used by everyone, but sometimes they may be forgotten. I summarize here for your reference~~~
Like it and watch it first, make it a habit~~~
The title traverses a range of numbers
for i in xrange(6):
print i ** 2
xrange will return an iterator, which is used to traverse a range one value at a time, which saves more memory than range. Xrange has been renamed range in python3.
Iterate over the collection
colors = ['red', 'green', 'blue', 'yellow']
for color in colors:
print color
Traverse the collection in reverse
for color in reversed(colors):
print color
Traverse the collection and its subscripts
for i, color in enumerate(colors):
print i, '-->', color
Traverse two sets
names = ['raymond', 'rachel', 'mattthew']
colors = ['red', 'green', 'blue', 'yellow']
for name, color in izip(names, colors):
print name, '-->', color
Zip generates a new list in memory and requires more memory. izip is more efficient than zip. In python3, izip was renamed to zip, replacing the original zip as a built-in function.
Orderly traversal
colors = ['red', 'green', 'blue', 'yellow']
for color in sorted(colors):
print color
for color in sorted(coloes, reverse = True):
print color
Custom sort order
colors = ['red', 'green', 'blue', 'yellow']
print sorted(colors, key=len)
List comprehensions and generators
print sum(i ** 2 for i in xrange(10))
Identify multiple exit points within the loop
def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
return -1
return i
Separate temporary context
with open('help.txt', 'w') as f:
with redirect_stdout(f):
help(pow)
The above code is used to demonstrate how to temporarily redirect standard output to a file, and then return to normal. Note that redirect_stdout was added in python3.4.
Open and close files
with open('data.txt') as f:
data = f.read()
Use lock
lock = threading.Lock()
with lock:
print 'critical section 1'
print 'critical section 2'
Count with dictionary
colors = ['red', 'green', 'red', 'blue', 'green', 'red']
d = {
}
for color in colors:
d[color] = d.get(color, 0) + 1
d = defaultdict(int)
for color in colors:
d[color] += 1
Resource portal
- attention【Be a tender programmer】No public
- in【Be a tender programmer】Backstage reply of public account【python data】【2020 Autumn Recruitment】 You can get the corresponding surprise!
「❤️ Thank you everyone」
- Like to support it, so that more people can see this content (If you don’t like it, it’s all hooligans-_-)
- Welcome to share your thoughts with me in the message area, and you are welcome to record your thought process in the message area.