text stringlengths 4 1.08k |
|---|
"generate all possible string permutations of each two elements in list `['hel', 'lo', 'bye']`","print([''.join(a) for a in combinations(['hel', 'lo', 'bye'], 2)])" |
get a list of items form nested list `li` where third element of each item contains string 'ar',[x for x in li if 'ar' in x[2]] |
Sort lists in the list `unsorted_list` by the element at index 3 of each list,unsorted_list.sort(key=lambda x: x[3]) |
Log message 'test' on the root logger.,logging.info('test') |
"Return a subplot axes positioned by the grid definition `1,1,1` using matpotlib","fig.add_subplot(1, 1, 1)" |
Sort dictionary `x` by value in ascending order,"sorted(list(x.items()), key=operator.itemgetter(1))" |
Sort dictionary `dict1` by value in ascending order,"sorted(dict1, key=dict1.get)" |
Sort dictionary `d` by value in descending order,"sorted(d, key=d.get, reverse=True)" |
Sort dictionary `d` by value in ascending order,"sorted(list(d.items()), key=(lambda x: x[1]))" |
elementwise product of 3d arrays `A` and `B`,"np.einsum('ijk,ikl->ijl', A, B)" |
Print a string `card` with string formatting,print('I have: {0.price}'.format(card)) |
Write a comment `# Data for Class A\n` to a file object `f`,f.write('# Data for Class A\n') |
move the last item in list `a` to the beginning,a = a[-1:] + a[:-1] |
Parse DateTime object `datetimevariable` using format '%Y-%m-%d',datetimevariable.strftime('%Y-%m-%d') |
Normalize line ends in a string 'mixed',"mixed.replace('\r\n', '\n').replace('\r', '\n')" |
find the real user home directory using python,os.path.expanduser('~user') |
index a list `L` with another list `Idx`,T = [L[i] for i in Idx] |
get a list of words `words` of a file 'myfile',words = open('myfile').read().split() |
Get a list of lists with summing the values of the second element from each list of lists `data`,[[sum([x[1] for x in i])] for i in data] |
summing the second item in a list of lists of lists,[sum([x[1] for x in i]) for i in data] |
sort objects in `Articles` in descending order of counts of `likes`,Article.objects.annotate(like_count=Count('likes')).order_by('-like_count') |
return a DateTime object with the current UTC date,today = datetime.datetime.utcnow().date() |
create a list containing the multiplication of each elements at the same index of list `lista` and list `listb`,"[(a * b) for a, b in zip(lista, listb)]" |
fetch smilies matching regex pattern '(?::|;|=)(?:-)?(?:\\)|\\(|D|P)' in string `s`,"re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', s)" |
match the pattern '[:;][)(](?![)(])' to the string `str`,"re.match('[:;][)(](?![)(])', str)" |
convert a list of objects `list_name` to json string `json_string`,json_string = json.dumps([ob.__dict__ for ob in list_name]) |
create a list `listofzeros` of `n` zeros,listofzeros = [0] * n |
decode the string 'stringnamehere' to UTF-8,"stringnamehere.decode('utf-8', 'ignore')" |
Match regex pattern '((?:A|B|C)D)' on string 'BDE',"re.findall('((?:A|B|C)D)', 'BDE')" |
Create a key `key` if it does not exist in dict `dic` and append element `value` to value.,"dic.setdefault(key, []).append(value)" |
Get the value of the minimum element in the second column of array `a`,"a[np.argmin(a[:, (1)])]" |
extend dictionary `a` with key/value pairs of dictionary `b`,a.update(b) |
removing key values pairs with key 'mykey1' from a list of dictionaries `mylist`,"[{k: v for k, v in d.items() if k != 'mykey1'} for d in mylist]" |
Removing key values pairs from a list of dictionaries,"[dict((k, v) for k, v in d.items() if k != 'mykey1') for d in mylist]" |
create 3 by 3 matrix of random numbers,"numpy.random.random((3, 3))" |
make new column 'C' in panda dataframe by adding values from other columns 'A' and 'B',df['C'] = df['A'] + df['B'] |
create a list of values from the dictionary `programs` that have a key with a case insensitive match to 'new york',"[value for key, value in list(programs.items()) if 'new york' in key.lower()]" |
append a path `/path/to/main_folder` in system path,sys.path.append('/path/to/main_folder') |
get all digits in a string `s` after a '[' character,"re.findall('\\d+(?=[^[]+$)', s)" |
python pickle/unpickle a list to/from a file 'afile',"pickle.load(open('afile', 'rb'))" |
Clicking a link using selenium using python,driver.find_element_by_xpath('xpath').click() |
count unique index values in column 'A' in pandas dataframe `ex`,ex.groupby(level='A').agg(lambda x: x.index.get_level_values(1).nunique()) |
Create a pandas dataframe of values from a dictionary `d` which contains dictionaries of dictionaries,"pd.concat(map(pd.DataFrame, iter(d.values())), keys=list(d.keys())).stack().unstack(0)" |
find out the number of non-matched elements at the same index of list `a` and list `b`,"sum(1 for i, j in zip(a, b) if i != j)" |
make all keys lowercase in dictionary `d`,"d = {(a.lower(), b): v for (a, b), v in list(d.items())}" |
sort list `list_` based on first element of each tuple and by the length of the second element of each tuple,"list_.sort(key=lambda x: [x[0], len(x[1]), x[1]])" |
trim whitespace in string `s`,s.strip() |
trim whitespace (including tabs) in `s` on the left side,s = s.lstrip() |
trim whitespace (including tabs) in `s` on the right side,s = s.rstrip() |
trim characters ' \t\n\r' in `s`,s = s.strip(' \t\n\r') |
trim whitespaces (including tabs) in string `s`,"print(re.sub('[\\s+]', '', s))" |
"In Django, filter `Task.objects` based on all entities in ['A', 'P', 'F']","Task.objects.exclude(prerequisites__status__in=['A', 'P', 'F'])" |
Change background color in Tkinter,root.configure(background='black') |
convert dict `result` to numpy structured array,"numpy.array([(key, val) for key, val in result.items()], dtype)" |
Concatenate dataframe `df_1` to dataframe `df_2` sorted by values of the column 'y',"pd.concat([df_1, df_2.sort_values('y')])" |
replace the last occurence of an expression '</div>' with '</bad>' in a string `s`,"re.sub('(.*)</div>', '\\1</bad>', s)" |
get the maximum of 'salary' and 'bonus' values in a dictionary,"print(max(d, key=lambda x: (d[x]['salary'], d[x]['bonus'])))" |
Filter Django objects by `author` with ids `1` and `2`,Book.objects.filter(author__id=1).filter(author__id=2) |
split string 'fooxyzbar' based on case-insensitive matching using string 'XYZ',"re.compile('XYZ', re.IGNORECASE).split('fooxyzbar')" |
get list of sums of neighboring integers in string `example`,"[sum(map(int, s)) for s in example.split()]" |
Get all the keys from dictionary `y` whose value is `1`,[i for i in y if y[i] == 1] |
converting byte string `c` in unicode string,c.decode('unicode_escape') |
unpivot first 2 columns into new columns 'year' and 'value' from a pandas dataframe `x`,"pd.melt(x, id_vars=['farm', 'fruit'], var_name='year', value_name='value')" |
"add key ""item3"" and value ""3"" to dictionary `default_data `",default_data['item3'] = 3 |
"add key ""item3"" and value ""3"" to dictionary `default_data `","default_data.update({'item3': 3, })" |
"add key value pairs 'item4' , 4 and 'item5' , 5 to dictionary `default_data`","default_data.update({'item4': 4, 'item5': 5, })" |
Get the first and last 3 elements of list `l`,l[:3] + l[-3:] |
reset index to default in dataframe `df`,df = df.reset_index(drop=True) |
"For each index `x` from 0 to 3, append the element at index `x` of list `b` to the list at index `x` of list a.",[a[x].append(b[x]) for x in range(3)] |
get canonical path of the filename `path`,os.path.realpath(path) |
check if dictionary `L[0].f.items()` is in dictionary `a3.f.items()`,set(L[0].f.items()).issubset(set(a3.f.items())) |
find all the indexes in a Numpy 2D array where the value is 1,zip(*np.where(a == 1)) |
How to find the index of a value in 2d array in Python?,np.where(a == 1) |
Collapse hierarchical column index to level 0 in dataframe `df`,df.columns = df.columns.get_level_values(0) |
"create a matrix from a list `[1, 2, 3]`","x = scipy.matrix([1, 2, 3]).transpose()" |
add character '@' after word 'get' in string `text`,"text = re.sub('(\\bget\\b)', '\\1@', text)" |
get a numpy array that contains the element wise minimum of three 3x1 arrays,"np.array([np.arange(3), np.arange(2, -1, -1), np.ones((3,))]).min(axis=0)" |
add a column 'new_col' to dataframe `df` for index in range,"df['new_col'] = list(range(1, len(df) + 1))" |
set environment variable 'DEBUSSY' equal to 1,os.environ['DEBUSSY'] = '1' |
Get a environment variable `DEBUSSY`,print(os.environ['DEBUSSY']) |
set environment variable 'DEBUSSY' to '1',os.environ['DEBUSSY'] = '1' |
"update dictionary `b`, overwriting values where keys are identical, with contents of dictionary `d`",b.update(d) |
get all the values in column `b` from pandas data frame `df`,df['b'] |
"make a line plot with errorbars, `ebar`, from data `x, y, err` and set color of the errorbars to `y` (yellow)","ebar = plt.errorbar(x, y, yerr=err, ecolor='y')" |
find all files with extension '.c' in directory `folder`,results += [each for each in os.listdir(folder) if each.endswith('.c')] |
add unicode string '1' to UTF-8 decoded string '\xc2\xa3',print('\xc2\xa3'.decode('utf8') + '1') |
lower-case the string obtained by replacing the occurrences of regex pattern '(?<=[a-z])([A-Z])' in string `s` with eplacement '-\\1',"re.sub('(?<=[a-z])([A-Z])', '-\\1', s).lower()" |
Setting stacksize in a python script,os.system('ulimit -s unlimited; some_executable') |
format a string `num` using string formatting,"""""""{0:.3g}"""""".format(num)" |
append the first element of array `a` to array `a`,"numpy.append(a, a[0])" |
return the column for value 38.15 in dataframe `df`,"df.ix[:, (df.loc[0] == 38.15)].columns" |
merge 2 dataframes `df1` and `df2` with same values in a column 'revenue' with and index 'date',df2['revenue'] = df2.CET.map(df1.set_index('date')['revenue']) |
load a json data `json_string` into variable `json_data`,json_data = json.loads(json_string) |
convert radians 1 to degrees,math.cos(math.radians(1)) |
count the number of integers in list `a`,"sum(isinstance(x, int) for x in a)" |
replacing '\u200b' with '*' in a string using regular expressions,"'used\u200b'.replace('\u200b', '*')" |
run function 'SudsMove' simultaneously,threading.Thread(target=SudsMove).start() |
sum of squares values in a list `l`,sum(i * i for i in l) |
calculate the sum of the squares of each value in list `l`,"sum(map(lambda x: x * x, l))" |
Create a dictionary `d` from list `iterable`,"d = dict(((key, value) for (key, value) in iterable))" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.