text
stringlengths
4
1.08k
How do I sort a zipped list in Python?,zipped.sort(key=lambda t: t[1])
Sorting a dictionary 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.find_all('div', class_='crBlock ')"
Remove list of indices from a list in Python,"[element for i, element in enumerate(centroids) if i not in index]"
Comparing two lists in Python,list(set(listA) & set(listB))
http file downloading and saving,"testfile = urllib.request.URLopener()
testfile.retrieve('http://randomsite.com/file.gz', 'file.gz')"
http file downloading and saving,"urllib.request.urlretrieve('http://randomsite.com/file.gz', 'file.gz')"
http file downloading and saving,file_name = wget.download(file_url)
Accented characters in Matplotlib,"ax.set_yticklabels(['\xe9', '\xe3', '\xe2'])"
How to get a list of all integer points in an n-dimensional cube using python?,"list(itertools.product(list(range(-x, y)), repeat=dim))"
How can I convert a unicode string into string literals in Python 2.7?,print(s.encode('unicode_escape'))
python - How to format variable number of arguments into a string?,"'Hello %s' % ', '.join(my_args)"
Python regex search AND split,"re.split('(ddd)', 'aaa bbb ccc ddd eee fff', 1)"
Python regex search AND split,"re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1)"
Convert list of dictionaries to Dataframe,pd.DataFrame(d)
How to split string into words that do not contain whitespaces in python?,"""""""This is a string"""""".split()"
How to split string into words that do not contain whitespaces in python?,"""""""This is a string"""""".split()"
python pandas: apply a function with arguments to a series,"my_series.apply(your_function, args=(2, 3, 4), extra_kw=1)"
Python: How to remove all duplicate items from a list,woduplicates = list(set(lseperatedOrblist))
Sum of product of combinations in a list,"sum([(i * j) for i, j in list(itertools.combinations(l, 2))])"
Using variables in Python regular expression,re.compile('{}-\\d*'.format(user))
"In Python, how do I convert all of the items in a list to floats?",[float(i) for i in lst]
How can I multiply all items in a list together with Python?,"from functools import reduce
reduce(lambda x, y: x * y, [1, 2, 3, 4, 5, 6])"
How to write a tuple of tuples to a CSV file using Python,writer.writerow(A)
How to write a tuple of tuples to a CSV file using Python,writer.writerows(A)
"python, format string","""""""{} %s {}"""""".format('foo', 'bar')"
Replace a string in list of lists,"example = [x.replace('\r\n', '') for x in example]"
Python: split elements of a list,[i.partition('\t')[-1] for i in l if '\t' in i]
Splitting a string by using two substrings in Python,"re.search('Test(.*)print', testStr, re.DOTALL)"
"python, locating and clicking a specific button with selenium",next = driver.find_element_by_css_selector('li.next>a')
Getting file size in Python?,os.stat('C:\\Python27\\Lib\\genericpath.py').st_size
how do i return a string from a regex match in python,"imtag = re.match('<img.*?>', line).group(0)"
How to change folder names in python?,"os.rename('Joe Blow', 'Blow, Joe')"
How to find overlapping matches with a regexp?,"re.findall('(?=(\\w\\w))', 'hello')"
express binary literals,bin(173)
express binary literals,"int('01010101111', 2)"
express binary literals,"int('010101', 2)"
express binary literals,"int('0b0010101010', 2)"
express binary literals,bin(21)
express binary literals,"int('11111111', 2)"
Delete digits in Python (Regex),"re.sub('$\\d+\\W+|\\b\\d+\\b|\\W+\\d+$', '', s)"
Delete digits in Python (Regex),"re.sub('\\b\\d+\\b', '', s)"
Delete digits in Python (Regex),"s = re.sub('^\\d+\\s|\\s\\d+\\s|\\s\\d+$', ' ', s)"
Python Split String,"s.split(':', 1)[1]"
How can I split this comma-delimited string in Python?,"print(s.split(','))"
How can I split this comma-delimited string in Python?,"mystring.split(',')"
How to remove parentheses only around single words in a string,"re.sub('\\((\\w+)\\)', '\\1', s)"
how to open a url in python,webbrowser.open_new(url)
how to open a url in python,webbrowser.open('http://example.com')
PyQt QPushButton Background color,self.pushButton.setStyleSheet('background-color: red')
Zip and apply a list of functions over a list of values in Python,"[x(y) for x, y in zip(functions, values)]"
How do I modify the width of a TextCtrl in wxPython?,"wx.TextCtrl(self, -1, size=(300, -1))"
Displaying a grayscale Image,"imshow(imageArray, cmap='Greys_r')"
How can I replace all the NaN values with Zero's in a column of a pandas dataframe,df.fillna(0)
how to export a table dataframe in pyspark to csv?,df.toPandas().to_csv('mycsv.csv')
how to export a table dataframe in pyspark to csv?,df.write.csv('mycsv.csv')
Sum the second value of each tuple in a list,sum(x[1] for x in structure)
How to sum the nlargest() integers in groupby,df.groupby('STNAME')['COUNTY_POP'].agg(lambda x: x.nlargest(3).sum())
what would be the python code to add time to a specific timestamp?,"datetime.strptime('21/11/06 16:30', '%d/%m/%y %H:%M')"
How to properly determine current script directory in Python?,os.path.dirname(os.path.abspath(__file__))
How can I do multiple substitutions using regex in python?,"re.sub('(.)', '\\1\\1', text.read(), 0, re.S)"
Python convert tuple to string,""""""""""""".join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))"
How to get full path of current file's directory in Python?,os.path.dirname(os.path.abspath(__file__))
variable number of digit in format string,"""""""{0:.{1}%}"""""".format(value, digits)"
Get current URL in Python,self.request.url
Print a variable selected by a random number,random_choice = random.choice(choices)
Python: Sum string lengths,length = sum(len(s) for s in strings)
Sort a list by multiple attributes?,"s = sorted(s, key=lambda x: (x[1], x[2]))"
Sort a list by multiple attributes?,"s.sort(key=operator.itemgetter(1, 2))"
How to disable query cache with mysql.connector,con.commit()
Filtering a list of strings based on contents,[k for k in lst if 'ab' in k]
How do I find the first letter of each word?,output = ''.join(item[0].upper() for item in input.split())
Get name of primary field of Django model,CustomPK._meta.pk.name
How to count the number of words in a sentence?,len(s.split())
numpy matrix vector multiplication,"np.einsum('ji,i->j', a, b)"
check what version of Python is running,sys.version
check what version of Python is running,sys.version_info
Format number using LaTeX notation in Python,print('\\num{{{0:.2g}}}'.format(1000000000.0))
Python initializing a list of lists,x = [[] for i in range(3)]
How to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?,{{my_variable | forceescape | linebreaks}}
Split a list of tuples into sub-lists of the same tuple field,"zip(*[(1, 4), (2, 5), (3, 6)])"
Split a list of tuples into sub-lists of the same tuple field,"[list(group) for key, group in itertools.groupby(data, operator.itemgetter(1))]"
How can I turn a string into a list in Python?,list('hello')
pandas dataframe create new columns and fill with calculated values from same df,df['A_perc'] = df['A'] / df['sum']
Getting a list of all subdirectories in the current directory,os.walk(directory)
Getting a list of all subdirectories in the current directory,[x[0] for x in os.walk(directory)]
How to filter a dictionary in Python?,"{i: 'updated' for i, j in list(d.items()) if j != 'None'}"
How to filter a dictionary in Python?,"dict((k, 'updated') for k, v in d.items() if v is None)"
How to filter a dictionary in Python?,"dict((k, 'updated') for k, v in d.items() if v != 'None')"
How to count number of rows in a group in pandas group by object?,df.groupby(key_columns).size()
python sum the values of lists of list,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)
2D array of objects in Python,nodes = [[Node() for j in range(cols)] for i in range(rows)]
How to replace (or strip) an extension from a filename in Python?,print(os.path.splitext('/home/user/somefile.txt')[0] + '.jpg')
How to get the resolution of a monitor in Pygame?,"pygame.display.set_mode((0, 0), pygame.FULLSCREEN)"
How can I format a float using matplotlib's LaTeX formatter?,"ax.set_title('$%s \\times 10^{%s}$' % ('3.5', '+20'))"
Print file age in seconds using Python,print(os.path.getmtime('/tmp'))
(Django) how to get month name?,today.strftime('%B')