text
stringlengths 4
1.08k
|
|---|
convert hex triplet string `rgbstr` to rgb tuple,"struct.unpack('BBB', rgbstr.decode('hex'))"
|
"Check if 3 is not in a list [2, 3, 4]","(3 not in [2, 3, 4])"
|
"Check if tuple (2, 3) is not in a list [(2, 3), (5, 6), (9, 1)]","((2, 3) not in [(2, 3), (5, 6), (9, 1)])"
|
"Check if tuple (2, 3) is not in a list [(2, 7), (7, 3), ""hi""]","((2, 3) not in [(2, 7), (7, 3), 'hi'])"
|
"Check if 3 is not in the list [4,5,6]","(3 not in [4, 5, 6])"
|
create a list by appending components from list `a` and reversed list `b` interchangeably,"[value for pair in zip(a, b[::-1]) for value in pair]"
|
delete the last column of numpy array `a` and assign resulting array to `b`,"b = np.delete(a, -1, 1)"
|
commit all the changes after executing a query.,dbb.commit()
|
join two dataframes based on values in selected columns,"pd.merge(a, b, on=['A', 'B'], how='outer')"
|
set text color as `red` and background color as `#A3C1DA` in qpushbutton,setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')
|
find the mean of elements in list `l`,sum(l) / float(len(l))
|
Find all the items from a dictionary `D` if the key contains the string `Light`,"[(k, v) for k, v in D.items() if 'Light' in k]"
|
Get a md5 hash from string `thecakeisalie`,k = hashlib.md5('thecakeisalie').hexdigest()
|
sort datetime objects `birthdays` by `month` and `day`,"birthdays.sort(key=lambda d: (d.month, d.day))"
|
extract table data from table `rows` using beautifulsoup,[[td.findNext(text=True) for td in tr.findAll('td')] for tr in rows]
|
strip the string `.txt` from anywhere in the string `Boat.txt.txt`,"""""""Boat.txt.txt"""""".replace('.txt', '')"
|
get a list of the row names from index of a pandas data frame,list(df.index)
|
get the row names from index in a pandas data frame,df.index
|
create a list of all unique characters in string 'aaabcabccd',""""""""""""".join(list(OrderedDict.fromkeys('aaabcabccd').keys()))"
|
get list of all unique characters in a string 'aaabcabccd',list(set('aaabcabccd'))
|
find rows with non zero values in a subset of columns where `df.dtypes` is not equal to `object` in pandas dataframe,"df.loc[(df.loc[:, (df.dtypes != object)] != 0).any(1)]"
|
"check if dictionary `d` contains all keys in list `['somekey', 'someotherkey', 'somekeyggg']`","all(word in d for word in ['somekey', 'someotherkey', 'somekeyggg'])"
|
"hide output of subprocess `['espeak', text]`","subprocess.check_output(['espeak', text], stderr=subprocess.STDOUT)"
|
replace nans by preceding values in pandas dataframe `df`,"df.fillna(method='ffill', inplace=True)"
|
create 4 numbers in range between 1 and 3,"print(np.linspace(1, 3, num=4, endpoint=False))"
|
Create numpy array of `5` numbers starting from `1` with interval of `3`,"print(np.linspace(1, 3, num=5))"
|
create a symlink directory `D:\\testdirLink` for directory `D:\\testdir` with unicode support using ctypes library,"kdll.CreateSymbolicLinkW('D:\\testdirLink', 'D:\\testdir', 1)"
|
get a list `slice` of array slices of the first two rows and columns from array `arr`,"slice = [arr[i][0:2] for i in range(0, 2)]"
|
upload uploaded file from path '/upload' to Google cloud storage 'my_bucket' bucket,"upload_url = blobstore.create_upload_url('/upload', gs_bucket_name='my_bucket')"
|
change directory to the directory of a python script,os.chdir(os.path.dirname(__file__))
|
call a function with argument list `args`,func(*args)
|
split column 'AB' in dataframe `df` into two columns by first whitespace ' ',"df['AB'].str.split(' ', 1, expand=True)"
|
"pandas dataframe, how do i split a column 'AB' into two 'A' and 'B' on delimiter ' '","df['A'], df['B'] = df['AB'].str.split(' ', 1).str"
|
sort list `xs` based on the length of its elements,"print(sorted(xs, key=len))"
|
sort list `xs` in ascending order of length of elements,"xs.sort(lambda x, y: cmp(len(x), len(y)))"
|
sort list of strings `xs` by the length of string,xs.sort(key=lambda s: len(s))
|
plot point marker '.' on series `ts`,ts.plot(marker='.')
|
get all combination of n binary values,"lst = list(itertools.product([0, 1], repeat=n))"
|
get all combination of n binary values,"lst = map(list, itertools.product([0, 1], repeat=n))"
|
get all combination of 3 binary values,"bin = [0, 1]
|
[(x, y, z) for x in bin for y in bin for z in bin]"
|
get all combination of 3 binary values,"lst = list(itertools.product([0, 1], repeat=3))"
|
append string 'str' at the beginning of each value in column 'col' of dataframe `df`,df['col'] = 'str' + df['col'].astype(str)
|
"get a dict of variable names `['some', 'list', 'of', 'vars']` as a string and their values","dict((name, eval(name)) for name in ['some', 'list', 'of', 'vars'])"
|
add a colorbar to plot `plt` using image `im` on axes `ax`,"plt.colorbar(im, ax=ax)"
|
convert nested list 'Cards' into a flat list,[a for c in Cards for b in c for a in b]
|
create a list containing keys of dictionary `d` and sort it alphabetically,"sorted(d, key=d.get)"
|
print the number of occurences of not `none` in a list `lst` in Python 2,print(len([x for x in lst if x is not None]))
|
lookup dictionary key `key1` in Django template `json`,{{json.key1}}
|
remove duplicates from list `myset`,mynewlist = list(myset)
|
"get unique values from the list `['a', 'b', 'c', 'd']`","set(['a', 'b', 'c', 'd'])"
|
"set size of `figure` to landscape A4 i.e. `11.69, 8.27` inches","figure(figsize=(11.69, 8.27))"
|
get every thing after last `/`,"url.rsplit('/', 1)"
|
get everything after last slash in a url stored in variable 'url',"url.rsplit('/', 1)[-1]"
|
open file '5_1.txt' in directory `direct`,"x_file = open(os.path.join(direct, '5_1.txt'), 'r')"
|
create a list with the characters of a string `5+6`,list('5+6')
|
concatenate a list of numpy arrays `input_list` together into a flattened list of values,np.concatenate(input_list).ravel().tolist()
|
convert dictionary `dict` into a flat list,print([y for x in list(dict.items()) for y in x])
|
Convert a dictionary `dict` into a list with key and values as list items.,[y for x in list(dict.items()) for y in x]
|
get a random record from model 'MyModel' using django's orm,MyModel.objects.order_by('?').first()
|
change current working directory to directory 'chapter3',os.chdir('chapter3')
|
change current working directory,os.chdir('C:\\Users\\username\\Desktop\\headfirstpython\\chapter3')
|
change current working directory,os.chdir('.\\chapter3')
|
create a flat dictionary by summing values associated with similar keys in each dictionary of list `dictlist`,"dict((key, sum(d[key] for d in dictList)) for key in dictList[0])"
|
sort pandas data frame `df` using values from columns `c1` and `c2` in ascending order,"df.sort(['c1', 'c2'], ascending=[True, True])"
|
Converting string lists `s` to float list,floats = [float(x) for x in s.split()]
|
Converting string lists `s` to float list,"floats = map(float, s.split())"
|
"set labels `[1, 2, 3, 4, 5]` on axis X in plot `plt`","plt.xticks([1, 2, 3, 4, 5])"
|
read line by line from stdin,"for line in fileinput.input():
|
pass"
|
read line by line from stdin,"for line in sys.stdin:
|
pass"
|
check if string `one` exists in the values of dictionary `d`,'one' in list(d.values())
|
Check if value 'one' is among the values of dictionary `d`,'one' in iter(d.values())
|
call parent class `Instructor` of child class constructor,"super(Instructor, self).__init__(name, year)"
|
create a dictionary using two lists`x` and `y`,"dict(zip(x, y))"
|
sort a list of dictionaries `a` by dictionary values in descending order,"sorted(a, key=lambda i: list(i.values())[0], reverse=True)"
|
sorting a list of dictionary `a` by values in descending order,"sorted(a, key=dict.values, reverse=True)"
|
"Use multiple groupby and agg operations `sum`, `count`, `std` for pandas data frame `df`","df.groupby(level=0).agg(['sum', 'count', 'std'])"
|
"for a dictionary `a`, set default value for key `somekey` as list and append value `bob` in that key","a.setdefault('somekey', []).append('bob')"
|
sum values in list of dictionaries `example_list` with key 'gold',sum(item['gold'] for item in example_list)
|
get a sum of all values from key `gold` in a list of dictionary `example_list`,sum([item['gold'] for item in example_list])
|
Get all the values in key `gold` summed from a list of dictionary `myLIst`,sum(item['gold'] for item in myLIst)
|
writing string 'text to write\n' to file `f`,f.write('text to write\n')
|
Write a string `My String` to a file `file` including new line character,file.write('My String\n')
|
find consecutive segments from a column 'A' in a pandas data frame 'df',df.reset_index().groupby('A')['index'].apply(np.array)
|
get a relative path of file 'my_file' into variable `fn`,"fn = os.path.join(os.path.dirname(__file__), 'my_file')"
|
retrieve an element from a set `s` without removing it,e = next(iter(s))
|
execute a command in the command prompt to list directory contents of the c drive `c:\\',os.system('dir c:\\')
|
Make a auto scrolled window to the end of the list in gtk,"self.treeview.connect('size-allocate', self.treeview_changed)"
|
"check if 3 is inside list `[1, 2, 3]`","3 in [1, 2, 3]"
|
Represent DateTime object '10/05/2012' with format '%d/%m/%Y' into format '%Y-%m-%d',"datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d')"
|
convert a string literal `s` with values `\\` to raw string literal,"s = s.replace('\\', '\\\\')"
|
get output of script `proc`,print(proc.communicate()[0])
|
create a pandas data frame from list of nested dictionaries `my_list`,"pd.concat([pd.DataFrame(l) for l in my_list], axis=1).T"
|
delete all columns in DataFrame `df` that do not hold a non-zero value in its records,"df.loc[:, ((df != 0).any(axis=0))]"
|
sort a multidimensional array `a` by column with index 1,"sorted(a, key=lambda x: x[1])"
|
"split string `s` to list conversion by ','","[x.strip() for x in s.split(',')]"
|
Get a list of items in the list `container` with attribute equal to `value`,items = [item for item in container if item.attribute == value]
|
create a file 'filename' with each tuple in the list `mylist` written to a line,"open('filename', 'w').write('\n'.join('%s %s' % x for x in mylist))"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.