text stringlengths 4 1.08k |
|---|
regex search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(d(d)d)',"re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1)" |
convert a list of dictionaries `d` to pandas data frame,pd.DataFrame(d) |
"split string ""This is a string"" into words that do not contain whitespaces","""""""This is a string"""""".split()" |
"split string ""This is a string"" into words that does not contain whitespaces","""""""This is a string"""""".split()" |
remove all duplicate items from a list `lseperatedOrblist`,woduplicates = list(set(lseperatedOrblist)) |
sum of product of combinations in a list `l`,"sum([(i * j) for i, j in list(itertools.combinations(l, 2))])" |
regular expression for validating string 'user' containing a sequence of characters ending with '-' followed by any number of digits.,re.compile('{}-\\d*'.format(user)) |
convert all of the items in a list `lst` to float,[float(i) for i in lst] |
"multiply all items in a list `[1, 2, 3, 4, 5, 6]` together","from functools import reduce |
reduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6])" |
write a tuple of tuples `A` to a csv file using python,writer.writerow(A) |
Write all tuple of tuples `A` at once into csv file,writer.writerows(A) |
"python, format string ""{} %s {}"" to have 'foo' and 'bar' in the first and second positions","""""""{} %s {}"""""".format('foo', 'bar')" |
Truncate `\r\n` from each string in a list of string `example`,"example = [x.replace('\r\n', '') for x in example]" |
split elements of a list `l` by '\t',[i.partition('\t')[-1] for i in l if '\t' in i] |
search for regex pattern 'Test(.*)print' in string `testStr` including new line character '\n',"re.search('Test(.*)print', testStr, re.DOTALL)" |
find button that is in li class `next` and assign it to variable `next`,next = driver.find_element_by_css_selector('li.next>a') |
get the size of file 'C:\\Python27\\Lib\\genericpath.py',os.stat('C:\\Python27\\Lib\\genericpath.py').st_size |
return a string from a regex match with pattern '<img.*?>' in string 'line',"imtag = re.match('<img.*?>', line).group(0)" |
"Rename a folder `Joe Blow` to `Blow, Joe`","os.rename('Joe Blow', 'Blow, Joe')" |
find overlapping matches from a string `hello` using regex,"re.findall('(?=(\\w\\w))', 'hello')" |
convert 173 to binary string,bin(173) |
convert binary string '01010101111' to integer,"int('01010101111', 2)" |
convert binary string '010101' to integer,"int('010101', 2)" |
convert binary string '0b0010101010' to integer,"int('0b0010101010', 2)" |
convert 21 to binary string,bin(21) |
convert binary string '11111111' to integer,"int('11111111', 2)" |
delete all digits in string `s` that are not directly attached to a word character,"re.sub('$\\d+\\W+|\\b\\d+\\b|\\W+\\d+$', '', s)" |
delete digits at the end of string `s`,"re.sub('\\b\\d+\\b', '', s)" |
Delete self-contained digits from string `s`,"s = re.sub('^\\d+\\s|\\s\\d+\\s|\\s\\d+$', ' ', s)" |
truncate string `s` up to character ':',"s.split(':', 1)[1]" |
"print a string `s` by splitting with comma `,`","print(s.split(','))" |
"Create list by splitting string `mystring` using "","" as delimiter","mystring.split(',')" |
remove parentheses only around single words in a string `s` using regex,"re.sub('\\((\\w+)\\)', '\\1', s)" |
webbrowser open url `url`,webbrowser.open_new(url) |
webbrowser open url 'http://example.com',webbrowser.open('http://example.com') |
change the background colour of the button `pushbutton` to red,self.pushButton.setStyleSheet('background-color: red') |
apply a list of functions named 'functions' over a list of values named 'values',"[x(y) for x, y in zip(functions, values)]" |
modify the width of a text control as `300` keeping default height in wxpython,"wx.TextCtrl(self, -1, size=(300, -1))" |
display a grayscale image from array of pixels `imageArray`,"imshow(imageArray, cmap='Greys_r')" |
replace all the nan values with 0 in a pandas dataframe `df`,df.fillna(0) |
export a table dataframe `df` in pyspark to csv 'mycsv.csv',df.toPandas().to_csv('mycsv.csv') |
Write DataFrame `df` to csv file 'mycsv.csv',df.write.csv('mycsv.csv') |
get the sum of each second value from a list of tuple `structure`,sum(x[1] for x in structure) |
sum the 3 largest integers in groupby by 'STNAME' and 'COUNTY_POP',df.groupby('STNAME')['COUNTY_POP'].agg(lambda x: x.nlargest(3).sum()) |
Parse string '21/11/06 16:30' according to format '%d/%m/%y %H:%M',"datetime.strptime('21/11/06 16:30', '%d/%m/%y %H:%M')" |
get current script directory,os.path.dirname(os.path.abspath(__file__)) |
double each character in string `text.read()`,"re.sub('(.)', '\\1\\1', text.read(), 0, re.S)" |
"concatenate strings in tuple `('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')` into a single string",""""""""""""".join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))" |
get full path of current directory,os.path.dirname(os.path.abspath(__file__)) |
"variable number of digits `digits` in variable `value` in format string ""{0:.{1}%}""","""""""{0:.{1}%}"""""".format(value, digits)" |
get current requested url,self.request.url |
get a random item from list `choices`,random_choice = random.choice(choices) |
sum the length of all strings in a list `strings`,length = sum(len(s) for s in strings) |
sort a list `s` by first and second attributes,"s = sorted(s, key=lambda x: (x[1], x[2]))" |
sort a list of lists `s` by second and third element in each list.,"s.sort(key=operator.itemgetter(1, 2))" |
Mysql commit current transaction,con.commit() |
filtering out strings that contain 'ab' from a list of strings `lst`,[k for k in lst if 'ab' in k] |
find the first letter of each element in string `input`,output = ''.join(item[0].upper() for item in input.split()) |
get name of primary field `name` of django model `CustomPK`,CustomPK._meta.pk.name |
count the number of words in a string `s`,len(s.split()) |
multiply array `a` and array `b`respective elements then sum each row of the new array,"np.einsum('ji,i->j', a, b)" |
check python version,sys.version |
check python version,sys.version_info |
format number 1000000000.0 using latex notation,print('\\num{{{0:.2g}}}'.format(1000000000.0)) |
Initialize a list of empty lists `x` of size 3,x = [[] for i in range(3)] |
apply jinja2 filters `forceescape` and `linebreaks` on variable `my_variable`,{{my_variable | forceescape | linebreaks}} |
"zip a list of tuples `[(1, 4), (2, 5), (3, 6)]` into a list of tuples according to original tuple index","zip(*[(1, 4), (2, 5), (3, 6)])" |
split a list of tuples `data` into sub-lists of the same tuple field using itertools,"[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]" |
Convert a string into a list,list('hello') |
create new column `A_perc` in dataframe `df` with row values equal to the value in column `A` divided by the value in column `sum`,df['A_perc'] = df['A'] / df['sum'] |
getting a list of all subdirectories in the directory `directory`,os.walk(directory) |
get a list of all subdirectories in the directory `directory`,[x[0] for x in os.walk(directory)] |
update all values associated with key `i` to string 'updated' if value `j` is not equal to 'None' in dictionary `d`,"{i: 'updated' for i, j in list(d.items()) if j != 'None'}" |
Filter a dictionary `d` to remove keys with value None and replace other values with 'updated',"dict((k, 'updated') for k, v in d.items() if v is None)" |
Filter a dictionary `d` to remove keys with value 'None' and replace other values with 'updated',"dict((k, 'updated') for k, v in d.items() if v != 'None')" |
count number of rows in a group `key_columns` in pandas groupby object `df`,df.groupby(key_columns).size() |
return list `result` of sum of elements of each list `b` in list of lists `a`,result = [sum(b) for b in a] |
What's the best way to search for a Python dictionary value in a list of dictionaries?,any(d['site'] == 'Superuser' for d in data) |
create a 2D array of `Node` objects with dimensions `cols` columns and `rows` rows,nodes = [[Node() for j in range(cols)] for i in range(rows)] |
replace extension '.txt' in basename '/home/user/somefile.txt' with extension '.jpg',print(os.path.splitext('/home/user/somefile.txt')[0] + '.jpg') |
Set the resolution of a monitor as `FULLSCREEN` in pygame,"pygame.display.set_mode((0, 0), pygame.FULLSCREEN)" |
format float `3.5e+20` to `$3.5 \\times 10^{20}$` and set as title of matplotlib plot `ax`,"ax.set_title('$%s \\times 10^{%s}$' % ('3.5', '+20'))" |
Get the age of directory (or file) `/tmp` in seconds.,print(os.path.getmtime('/tmp')) |
how to get month name of datetime `today`,today.strftime('%B') |
get month name from a datetime object `today`,today.strftime('%B') |
Convert nested list `x` into a flat list,[j for i in x for j in i] |
get each value from a list of lists `a` using itertools,print(list(itertools.chain.from_iterable(a))) |
"convert date string 'January 11, 2010' into day of week","datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')" |
"remove item ""b"" in list `a`",a.remove('b') |
remove item `c` in list `a`,a.remove(c) |
delete the element 6 from list `a`,a.remove(6) |
delete the element 6 from list `a`,a.remove(6) |
Get all matching patterns 'a.*?a' from a string 'a 1 a 2 a 3 a 4 a'.,"re.findall('(?=(a.*?a))', 'a 1 a 2 a 3 a 4 a')" |
outer product of each column of a 2d `X` array to form a 3d array `X`,"np.einsum('ij,kj->jik', X, X)" |
Getting the last element of list `some_list`,some_list[(-1)] |
Getting the second to last element of list `some_list`,some_list[(-2)] |
gets the `n` th-to-last element in list `some_list`,some_list[(- n)] |
get the last element in list `alist`,alist[(-1)] |
get the last element in list `astr`,astr[(-1)] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.