This is a code memo that I often write in Python2.
Version: Confirmed with Python 2.7.6
str_util.py
#White space before and after
value.strip()
#String search
value.find('sub') #From before
value.rfind('sub') #From the back
#If not found-1 returned
value.index('sub') #From before
value.rindex('sub') #From the back
#index,ValueError if rindex is not found:Substring not found occurs.
#Uppercase and lowercase conversion of character strings
value.upper()
value.lower()
csv_util.py
import csv
w_f = open(output_file, 'w')
writer = csv.writer(w_f, lineterminator='\n') #It is better to specify the line feed code explicitly.
for record in records:
output_record = []
for item in record: #If record is in list format, it can be output as it is
output_record.append(item)
writer.writerow(output_record)
w_f.close()
freq_util.py
#Sort map by key(ascending order)
for key, value in sorted(map.items()):
print key, value
#Sort map by key(descending order)
for key, value in sorted(map.items(), reverse=True):
print key, value
#Sort map by value(ascending order)
for key, value in sorted(map.items(), key=lambda x:x[1]):
print key, value
#Sort map by value(descending order)
for key, value in sorted(map.items(), key=lambda x:x[1], reverse=True):
print key, value
#Frequency calculation using a counter
from collections import Counter
data_list = [.....]
counter = Counter(data_list)
for key, cnt in counter.most_common():
print key, cnt
#Top-Get 3
counter.most_common(3)
#Add by update 1
counter.update("aaa") #Breaked down into characters, Counter({'a': 3})Will be.
#Add by update 2
counter.update(["aaa"]) #Count up as a character string properly Counter({'a': 3, 'aaa': 1})
combi_util.py
import itertools
data = ['a', 'b', 'c', 'd', 'e']
#List 3 combinations from data.
list(itertools.combinations(data,3))
#Find the permutations in data.
list(itertools.permutations(data))
About range and xrange in Python2. If range (1,5) is set, the list [1, 2, 3, 4] will be returned, so memory will be allocated immediately. If the specified range is wide, the memory consumption is large. xrange returns an xrange object. When specifying a large range, it is better to specify this. In Python3, the range function seems to return a range object, so xrange seems to disappear.
python
>>> print range(1, 5)
[1, 2, 3, 4]
>>> print xrange(1, 5)
xrange(1, 5)
python
def get_unix_time(datetime_str, format):
datetime_obj = datetime.datetime.strptime(datetime_str, format)
return time.mktime(datetime_obj.timetuple())
get_unix_time('2014-12-22 14:03:10', '%Y-%m-%d %H:%M:%S')
python
def get_datetime_str(unix_time, format):
return datetime.datetime.fromtimestamp(unix_time).strftime(format)
Recommended Posts