list
List
[start(inclusive):end(exclusive)]
List[start:]
List[:end]
list_name.append('XXX')
method. However, if you want to combine a list with another array type (list, set, tuple), you
can use the list_name.extend('XXX') method on the list.
You can also use the list_name.index('XXX') method to find the position of an item in a list. You can then use that position to remove the item with the list_name.pop(position) method.
sorted(list_name)
Tuple
zip(list1, list2)
name1, name2 = Zipped_Tuple[0]
for name1, name2 in zipped_tuple
zip() function does just that. It will return a list of tuples containing one element from each
When looping over a list, you can also track your position in the list by using the enumerate() function. The function returns the index of the list item you are currently on in the list and the list item itself.
$ letters = ['A', 'B', 'C']
$ names =['a', 'b', 'c']
$ for index, letter in enumerate(letters, start = 1):
print(index, letter)
$ zip_list = list(zip(letters, names))
$ for z1, z2 in zip_list:
print(z1, z2)
$ z = zip(letters, names)
$ print(*z)
Type()
Set
Set1.union(set2): combine all
Set1.intersection.(set2): overlapping
Check items: len(set_name)
Set1.add(something)
Set1.difference(set2)
diff = set1 - set2
Dictionary
$ dictionary.get(Key_name): returns “none” if key does not exist
$ dictionary.get(Key_name, “Not Found”): returns “Not Found” if key does not exist
$ dict.keys()
$ for x,y in dictionary.items()
Dictionary[x] = y
$ sorted(dictionary, reverse=True): sort descend
$ dict1.update(dict2/tuple/list)
$ del dict[key_names]
$dict.pop(dict[key_names])
$ dict-removed = dict.pop(key-name)
To be safe $ dict-removed = dict.pop(key-name, {})
In: “2012” in dict: returns true or false
CSV
$ import csv
$ csvfile = open (‘xxxx.csv’,’r’)
$ for row in csv.reader(csvfile):
Print(row)
Counter
$ from collections import Counter
$ XXX=Counter(xxx)
$ XXX.most_common(3)
defaultdict
$ from collections import defaultdict
$ XXX=defaultdict(default_type): works just like a dict
# Create an empty dictionary: ridership
ridership = {}
# Iterate over the entries
for date, stop, riders in entries:
# Check to see if date is already in the ridership dictionary
if date not in ridership:
# Create an empty list for any missing date
ridership[date] = []
# Append the stop and riders as a tuple to the date keys list
ridership[date].append((stop,riders))
# Print the ridership for '03/09/2016'
print(ridership['03/09/2016'])
# Import defaultdict
from collections import defaultdict
# Create a defaultdict with a default type of list: ridership
ridership = defaultdict(list)
# Iterate over the entries
for data, stop, riders in entries:
# Use the stop as the key of ridership and append the riders to its value
ridership[stop].append(riders)
# Print the first 10 items of the ridership dictionary
print(list(ridership.items())[:10])
OrderedDict
$ from collections import OrderedDict
$ XXX= OrderedDict()
$ for item in dict:
XXX[itme['Key_name']]=item
$ print(list(XXX.items())[:3])
$ print(XXX.popitem()) print in reverse insertion order
$ print(XXX.popitem(last = False)) : return items in insertion order
namedtuple
$ from collection import namedtuple
$ name = namedtuple('letters', ['A', 'B' ,'C'])
$ letters = [ ]
$ for letter in dict:
detail = name(letter['A'], letter['B'], letter['C'])
letters.append(detail)
$ print (letters[0])
# Import namedtuple from collections
from collections import namedtuple
# Create the namedtuple: DateDetails
DateDetails = namedtuple('DateDetails', ['date', 'stop', 'riders'])
# Create the empty list: labeled_entries
labeled_entries = []
# Iterate over the entries list
for date, stop, riders in entries:
# Append a new DateDetails namedtuple instance for each entry to labeled_entries
labeled_entries.append(DateDetails(date,stop,riders))
# Print the first 5 items in labeled_entries
print(labeled_entries[:5])
# Iterate over the first twenty items in labeled_entries
for item in labeled_entries[:20]:
# Print each item's stop
print(item.stop)
# Print each item's date
print(item.date)
# Print each item's riders
print(item.riders)
datetime
$ from datetime import datetime
$ print(XX_date)
$ dt = datetime.strptime(XXX_date, '%m/%d/%Y' )
$ dt.strftime( '%m/%d/%Y' )
$ dt.isoformat(): ISO format
$ daily = defaultdict(int)
$ for item in certain_dict:
item_dt = datetime.strptime(item[4], '%m/%d/%Y')
daily[item_dt.day] += 1
$ local_dt = datetime.now() :returns time on the machine
$ local_dt = datetime.utcnow() : UTC time
$ from pytz import timezone
$ ny_tz = timezone('US/Estern')
$ ny_dt = dt_file_name.replace(tzinfo=ny_tz) : you can make a datetime object "aware" by passing a timezone as the tzinfo keyword argument
to the .replace() method on a datetime instance.
$ la_dt = ny_dt.astimezone(la_tz) :convert ny_dt to la timezone
$ from datetime import timedelta
$ flashback = timedelta(days=90)
$ print(record_dt)
$ print (record_dt + flashback)
$ print (record_dt - flashback)
$ time_diff = record_dt - record2_dt
$ type (time_diff) : datetime.timedelta
pendulum
$ import pendulum
$ occur = voilation[4] + ' ' + violation[5] + 'M'
$occur_dt = pendulum.parse(occur, tz = 'US/Eastern')
$ occur_dt = pendulum.parse(occur, strict = False)
$ for day_dt in day_dts:
print(day_dt.in_timezone('Asian/Tokyo'))
$print (pendulun.now('Asian/Tokyo'))
$ print(diff.in_words())
$ print(diff.in_days())
$ print(diff.in_hours())
csv
$ for row in csv.DictReader(csvfile)
print(row)
$ deleted_item = dict.pop(key_name_deleted)