text
stringlengths
4
1.08k
convert a string `a` of letters embedded in squared brackets into embedded lists,"[i.split() for i in re.findall('\\[([^\\[\\]]+)\\]', a)]"
extract dictionary `d` from list `a` where the value associated with the key 'name' of dictionary `d` is equal to 'pluto',[d for d in a if d['name'] == 'pluto']
extract dictionary from list of dictionaries based on a key's value.,[d for d in a if d['name'] == 'pluto']
Retrieve list of values from dictionary 'd',list(d.values())
replace occurrences of two whitespaces or more with one whitespace ' ' in string `s`,"re.sub(' +', ' ', s)"
Change the mode of file 'my_script.sh' to permission number 484,"os.chmod('my_script.sh', 484)"
write pandas dataframe `df` to the file 'c:\\data\\t.csv' without row names,"df.to_csv('c:\\data\\t.csv', index=False)"
remove all words which contains number from a string `words` using regex,"re.sub('\\w*\\d\\w*', '', words).strip()"
control the keyboard and mouse with dogtail in linux,"dogtail.rawinput.click(100, 100)"
parse date string '2009/05/13 19:19:30 -0400' using format '%Y/%m/%d %H:%M:%S %z',"datetime.strptime('2009/05/13 19:19:30 -0400', '%Y/%m/%d %H:%M:%S %z')"
Get the position of a regex match for word `is` in a string `String`,"re.search('\\bis\\b', String).start()"
Get the position of a regex match `is` in a string `String`,"re.search('is', String).start()"
input an integer tuple from user,"tuple(map(int, input().split(',')))"
input a tuple of integers from user,"tuple(int(x.strip()) for x in input().split(','))"
replace unicode character '\u2022' in string 'str' with '*',"str.decode('utf-8').replace('\u2022', '*').encode('utf-8')"
replace unicode characters ''\u2022' in string 'str' with '*',"str.decode('utf-8').replace('\u2022', '*')"
convert ndarray with shape 3x3 to array,"np.zeros((3, 3)).ravel()"
get os name,"import platform
platform.system()"
get os version,"import platform
platform.release()"
get the name of the OS,print(os.name)
What is the most pythonic way to exclude elements of a list that start with a specific character?,[x for x in my_list if not x.startswith('#')]
"replace fields delimited by braces {} in string ""Day old bread, 50% sale {0}"" with string 'today'","""""""Day old bread, 50% sale {0}"""""".format('today')"
Get a minimum value from a list of tuples `list` with values of type `string` and `float` with nan,"min(list, key=lambda x: float('inf') if math.isnan(x[1]) else x[1])"
Find average of a nested list `a`,a = [(sum(x) / len(x)) for x in zip(*a)]
Log info message 'Log message' with attributes `{'app_name': 'myapp'}`,"logging.info('Log message', extra={'app_name': 'myapp'})"
replace values of dataframe `df` with True if numeric,"df.applymap(lambda x: isinstance(x, (int, float)))"
sort list `l` based on its elements' digits,"sorted(l, key=lambda x: int(re.search('\\d+', x).group(0)))"
close the window in tkinter,self.root.destroy()
"get mean of columns `2, 5, 6, 7, 8` for all rows in dataframe `df`","df.iloc[:, ([2, 5, 6, 7, 8])].mean(axis=1)"
filter dataframe `df` by sub-level index '0630' in pandas,df[df.index.map(lambda x: x[1].endswith('0630'))]
flask-sqlalchemy delete row `page`,db.session.delete(page)
Format a string `u'Andr\xc3\xa9'` that has unicode characters,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9')"
convert a unicode 'Andr\xc3\xa9' to a string,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9').decode('utf8')"
list all files in directory `path`,os.listdir(path)
rename file `dir` to `dir` + '!',"os.rename(dir, dir + '!')"
Insert a character `-` after every two elements in a string `s`,"""""""-"""""".join(a + b for a, b in zip(s[::2], s[1::2]))"
printing numbers rounding up to third decimal place,print('%.3f' % 3.1415)
add variable `var` to key 'f' of first element in JSON data `data`,data[0]['f'] = var
get the path of module `a_module`,print(a_module.__file__)
get the path of the current python module,print(os.getcwd())
get the path of the python module `amodule`,path = os.path.abspath(amodule.__file__)
fill list `myList` with 4 0's,self.myList.extend([0] * (4 - len(self.myList)))
drop duplicate indexes in a pandas data frame `df`,df[~df.index.duplicated()]
unpack elements of list `i` as arguments into function `foo`,foo(*i)
generate list of numbers in specific format using string formatting precision.,[('%.2d' % i) for i in range(16)]
sort dictionary `mydict` in descending order based on the sum of each value in it,"sorted(iter(mydict.items()), key=lambda tup: sum(tup[1]), reverse=True)[:3]"
get top `3` items from a dictionary `mydict` with largest sum of values,"heapq.nlargest(3, iter(mydict.items()), key=lambda tup: sum(tup[1]))"
"get index of character 'b' in list '['a', 'b']'","['a', 'b'].index('b')"
set font size of axis legend of plot `plt` to 'xx-small',"plt.setp(legend.get_title(), fontsize='xx-small')"
extract the 2nd elements from a list of tuples,[x[1] for x in elements]
get the opposite diagonal of a numpy array `array`,np.diag(np.rot90(array))
flatten list of tuples `a`,list(chain.from_iterable(a))
substitute two or more whitespace characters with character '|' in string `line`,"re.sub('\\s{2,}', '|', line.strip())"
print float `a` with two decimal points,print(('%.2f' % a))
print float `a` with two decimal points,print(('{0:.2f}'.format(a)))
print float `a` with two decimal points,"print(('{0:.2f}'.format(round(a, 2))))"
print float `a` with two decimal points,"print(('%.2f' % round(a, 2)))"
limit float 13.9499999 to two decimal points,('%.2f' % 13.9499999)
limit float 3.14159 to two decimal points,('%.2f' % 3.14159)
limit float 13.949999999999999 to two decimal points,float('{0:.2f}'.format(13.95))
limit float 13.949999999999999 to two decimal points,'{0:.2f}'.format(13.95)
load a tsv file `c:/~/trainSetRel3.txt` into a pandas data frame,"DataFrame.from_csv('c:/~/trainSetRel3.txt', sep='\t')"
set UTC offset by 9 hrs ahead for date '2013/09/11 00:17',dateutil.parser.parse('2013/09/11 00:17 +0900')
"pass a list of parameters `((1, 2, 3),) to sql queue 'SELECT * FROM table WHERE column IN %s;'","cur.mogrify('SELECT * FROM table WHERE column IN %s;', ((1, 2, 3),))"
"sum all elements of two-dimensions list `[[1, 2, 3, 4], [2, 4, 5, 6]]]`","sum([sum(x) for x in [[1, 2, 3, 4], [2, 4, 5, 6]]])"
Retrieve an arbitrary value from dictionary `dict`,next(iter(dict.values()))
access an arbitrary value from dictionary `dict`,next(iter(list(dict.values())))
group dataframe `df` by columns 'Month' and 'Fruit',"df.groupby(['Month', 'Fruit']).sum().unstack(level=0)"
sort list `mylist` of tuples by arbitrary key from list `order`,"sorted(mylist, key=lambda x: order.index(x[1]))"
sort a list of dictionary `persons` according to the key `['passport']['birth_info']['date']`,"sorted(persons, key=lambda x: x['passport']['birth_info']['date'])"
remove the fragment identifier `#something` from a url `http://www.address.com/something#something`,urlparse.urldefrag('http://www.address.com/something#something')
download to a directory '/path/to/dir/filename.ext' from source 'http://example.com/file.ext',"urllib.request.urlretrieve('http://example.com/file.ext', '/path/to/dir/filename.ext')"
remove all duplicates from a list of sets `L`,list(set(frozenset(item) for item in L))
remove duplicates from a list of sets 'L',[set(item) for item in set(frozenset(item) for item in L)]
terminate process `p`,p.terminate()
delete all values in a list `mylist`,del mylist[:]
throw an error window in python in windows,"ctypes.windll.user32.MessageBoxW(0, 'Error', 'Error', 0)"
remove empty strings from list `str_list`,str_list = list([_f for _f in str_list if _f])
remove newlines and whitespace from string `yourstring`,"re.sub('[\\ \\n]{2,}', '', yourstring)"
remove the last dot and all text beyond it in string `s`,"re.sub('\\.[^.]+$', '', s)"
remove elements from an array `A` that are in array `B`,"A[np.all(np.any(A - B[:, (None)], axis=2), axis=0)]"
Write column 'sum' of DataFrame `a` to csv file 'test.csv',"a.to_csv('test.csv', cols=['sum'])"
"call a Python script ""test2.py""","exec(compile(open('test2.py').read(), 'test2.py', 'exec'))"
"call a Python script ""test1.py""","subprocess.call('test1.py', shell=True)"
sort a zipped list `zipped` using lambda function,"sorted(zipped, key=lambda x: x[1])"
sort a dictionary `y` by value then by key,"sorted(list(y.items()), key=lambda x: (x[1], x[0]), reverse=True)"
using beautifulsoup to select div blocks within html `soup`,"soup.find_all('div', class_='crBlock ')"
remove elements from list `centroids` the indexes of which are in array `index`,"[element for i, element in enumerate(centroids) if i not in index]"
list duplicated elements in two lists `listA` and `listB`,list(set(listA) & set(listB))
"download ""http://randomsite.com/file.gz"" from http and save as ""file.gz""","testfile = urllib.request.URLopener()
testfile.retrieve('http://randomsite.com/file.gz', 'file.gz')"
"download file from http url ""http://randomsite.com/file.gz"" and save as ""file.gz""","urllib.request.urlretrieve('http://randomsite.com/file.gz', 'file.gz')"
download file from http url `file_url`,file_name = wget.download(file_url)
"set an array of unicode characters `[u'\xe9', u'\xe3', u'\xe2']` as labels in Matplotlib `ax`","ax.set_yticklabels(['\xe9', '\xe3', '\xe2'])"
get a list of all integer points in a `dim` dimensional hypercube with coordinates from `-x` to `y` for all dimensions,"list(itertools.product(list(range(-x, y)), repeat=dim))"
convert unicode string `s` into string literals,print(s.encode('unicode_escape'))
how to format a list of arguments `my_args` into a string,"'Hello %s' % ', '.join(my_args)"
search and split string 'aaa bbb ccc ddd eee fff' by delimiter '(ddd)',"re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)"