set:
To add item to a set:
s.add(x)
To check whether item is in a set:
x in s #return True if set s contains item x
To remove item from a set:
s.remove(x)
This blog intends to document all computer science problems I encountered and my solutions/comments to them.
To add item to a set:
s.add(x)
x in s #return True if set s contains item x
s.remove(x)
#Extract first column while the lines are comma seperated
awk '{FS=","}{print $1}'
#Check whether second column is "Artists", if so, print first and second columns.
awk '{FS="\t"} $2 = "Artists" {print $1 "\t" $2}'
#!/bin/python3
# The goal of this script is to randomly choose n lines from a text files by line without duplicate
import sys, os, pdb, random
#The prefix will add to the front of each line
prefix = ""
if len(sys.argv) != 3 and len(sys.argv) != 4:
print("syntax: randomlines.py <input_file> <num_of_sample>")
sys.exit()
else:
input_file = sys.argv[1]
num_of_sample = int(sys.argv[2])
if len(sys.argv) == 4:
prefix = sys.argv[3]
#pdb.set_trace()
lines = open(input_file, "r").read().splitlines()
if len(lines) < num_of_sample:
print("The number of random lines you asked for is larger than the lines in the target file.\n" +
"Shrink it to lines of target file automatically.\n" +
"-----------------------------------------------\n")
num_of_sample = len(lines)
chosen_lines_num = random.sample(range(0,len(lines)), num_of_sample) #range(0,3) only generate 0,1,2
for i in chosen_lines_num:
print(prefix + lines[i])
sorted(adict.items(), key=lambda (k,v): v)
from operator import itemgetter
sorted(d.items(), key=itemgetter(1))
>>> x
{'a': [1, 2, 3], 'b': [0, 3, 1]}
>>> sorted(x.items(), key = (lambda k: k[0])) #sort by key
[('a', [1, 2, 3]), ('b', [0, 3, 1])]
>>> sorted(x.items(), key = (lambda k: k[1])) #sort by value
[('b', [0, 3, 1]), ('a', [1, 2, 3])]
>>> sorted(x.items(), key = (lambda k: k[1][0])) #sort by first item in value(a list)
[('b', [0, 3, 1]), ('a', [1, 2, 3])]
>>> sorted(x.items(), key = (lambda k: k[1][1])) #sort by second item in value(a list)
[('a', [1, 2, 3]), ('b', [0, 3, 1])]