text
stringlengths
4
1.08k
"create a list of tuples which contains number 9 and the number before it, for each occurrence of 9 in the list 'mylist'","[(x, y) for x, y in zip(myList, myList[1:]) if y == 9]"
how to create similarity matrix in numpy python?,np.cov(x)
default save path for python idle?,os.chdir(os.path.expanduser('~/Documents'))
is there a need to close files that have no reference to them?,"open(to_file, 'w').write(indata)"
python matching words with same index in string,"['I am', 'show']"
sorting while preserving order in python,"a_order, a_sorted = zip(*sorted(enumerate(a), key=lambda item: item[1]))"
using scikit-learn decisiontreeclassifier to cluster,"clf.fit(X, y)"
get a list of variables from module 'adfix.py' in current module.,print([item for item in dir(adfix) if not item.startswith('__')])
python pil: how to write png image to string,"image.save(output, format='GIF')"
how to sort a dictionary in python by value when the value is a list and i want to sort it by the first index of that list,"sorted(list(data.items()), key=lambda x: x[1][0])"
python: want to use a string as a slice specifier,slice(*[(int(i.strip()) if i else None) for i in string_slice.split(':')])
string regex two mismatches python,"re.findall('(?=(SS..|S.Q.|S..P|.SQ.|.S.P|..QP))', s)"
"can you create a python list from a string, while keeping characters in specific keywords together?","['x', 'y', 'z', 'car', 'bus', 'a', 'b', 'c', 'car']"
python web application,app.run()
how to get everything after last slash in a url?,"url.rsplit('/', 1)[-1]"
"sort a list of lists `list_to_sort` by indices 2,0,1 of the inner list","sorted_list = sorted(list_to_sort, key=itemgetter(2, 0, 1))"
how to run a python script from idle interactive shell?,"subprocess.check_output(['python', 'helloworld.py'])"
replace character 'a' with character 'e' and character 's' with character '3' in file `contents`,"newcontents = contents.replace('a', 'e').replace('s', '3')"
python - regex - special characters and n,"w = re.findall('[a-zA-Z\xd1\xf1]+', p.decode('utf-8'))"
appending to 2d lists in python,listy = [[] for i in range(3)]
how to change end-of-line conventions?,"df.to_csv('filename.txt', sep='\t', mode='wb', encoding='utf8')"
zip and apply a list of functions over a list of values in python,"[x(y) for x, y in zip(functions, values)]"
parsing html string `html` using beautifulsoup,"parsed_html = BeautifulSoup(html)
print(parsed_html.body.find('div', attrs={'class': 'container', }).text)"
what would be the most pythonic way to make an attribute that can be used in a lambda?,"lambda : setattr(self, 'spam', 'Ouch')"
python cleaning dates for conversion to year only in pandas,"df['datestart'] = pd.to_datetime(df['datestart'], coerce=True)"
compare elements of a list of lists and return a list,zip(*a)
sorting by nested dictionary in python dictionary,"srt_dict['searchResult'].sort(key=lambda d: d['ranking'], reverse=True)"
filter model 'entry' where 'id' is not equal to 3 in django,Entry.objects.filter(~Q(id=3))
pandas: slice a multiindex by range of secondary index,s['b'].iloc[1:10]
how to remove lines in a matplotlib plot,"pylab.setp(_self.ax.get_yticklabels(), fontsize=8)"
how to print utf-8 to console with python 3.4 (windows 8)?,print(text.encode('utf-8'))
how to optimize multiprocessing in python,multiprocessing.Process.__init__(self)
convert utf-8 with bom to utf-8 with no bom in python,s = u.encode('utf-8')
how can i copy the order of one array into another? [python],B[np.argsort(A)] = np.sort(B)
print multiple arguments in python,"print(('Total score for', name, 'is', score))"
limit float 13.9499999 to two decimal points,('%.2f' % 13.9499999)
python: merge two lists of dictionaries,"[{'x': 'one', 'id': 1}, {'x': 'two', 'id': 2}, {'x': 'three', 'id': 3}]"
pythonic way to check that the lengths of lots of lists are the same,"my_list = [[1, 2, 3], ['a', 'b'], [5, 6, 7]]"
drawing a correlation graph in matplotlib,plt.gcf().savefig('correlation.png')
django haystack - how to filter search results by a boolean field?,sqs.filter(has_been_sent=True)
cherrypy interferes with twisted shutting down on windows,"Thread(target=cherrypy.quickstart, args=[Root()]).start()"
parse string `s` to float or int,"try:
return int(s)
except ValueError:
return float(s)"
how do i avoid the capital placeholders in python's argparse module?,parser.print_help()
extract first and last row of a dataframe in pandas,"pd.concat([df.head(1), df.tail(1)])"
python initializing a list of lists,x = [[] for i in range(3)]
python: load words from file into a set,set(line.strip() for line in open('filename.txt'))
how to sort tire sizes in python,"['235/40/17', '285/30/18', '315/25/19', '275/30/19', '285/30/19']"
how to get status of uploading file in flask,"request.META['REMOTE_ADDR'], request.GET['X-Progress-ID']"
'negative' pattern matching in python,"matchObj = re.search('^(?!OK|\\.).*', item)"
python using getattr to call function with variable parameters,"getattr(foo, bar)(*params)"
escape string python for mysql,cursor.execute(sql)
how to convert this text file into a dictionary?,"{'labelA': 'thereissomethinghere', 'label_Bbb': 'hereaswell'}"
random string generation with upper case letters and digits in python,""""""""""""".join(random.choices(string.ascii_uppercase + string.digits, k=N))"
how do i create a line-break in terminal?,print('hello')
print current date and time in a regular format,datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
normalizing a list of numbers in python,norm = [(float(i) / sum(raw)) for i in raw]
a simple way to remove multiple spaces in a string in python,"re.sub(' +', ' ', 'The quick brown fox')"
printing lists onto tables in python,"print('\n'.join(' '.join(map(str, row)) for row in t))"
display attribute `attr` for each object `obj` in list `my_list_of_objs`,print([obj.attr for obj in my_list_of_objs])
print unicode string `ex\xe1mple` in uppercase,print('ex\xe1mple'.upper())
how to compile a string of python code into a module whose functions can be called?,foo()
using regular expression substitution command to insert leading zeros in front of numbers less than 10 in a string of filenames,"re.sub('[a-zA-Z]\\d,', lambda x: x.group(0)[0] + '0' + x.group(0)[1:], s)"
how to replace string values in pandas dataframe to integers?,stores['region'] = stores['region'].astype('category')
putting a variable inside a string (python),plot.savefig('hanning%(num)s.pdf' % locals())
how to delete a character from a string using python?,"newstr = oldstr.replace('M', '')"
how do i read a random line from one file in python?,print(random.choice(list(open('file.txt'))))
how to check if a string is at the beginning of line in spite of tabs or whitespaces?,"re.match('^\\s*word', line)"
python: converting radians to degrees,math.cos(math.radians(1))
list is a subset of another list,"set(map(tuple, listB)) <= set(map(tuple, listA))"
python: print a variable in hex,print(' '.join(hex(ord(n)) for n in my_hex))
python list comprehension to join list of lists,combined = list(itertools.chain.from_iterable(lists))
conditionally passing arbitrary number of default named arguments to a function,"func('arg', 'arg2', 'some value' if condition else None)"
pandas changing cell values based on another cell,df.loc[df['column_name'].isin(b)]
how to display the first few characters of a string in python?,"""""""This"""""""
execute terminal command from python in new terminal window?,"subprocess.call(['gnome-terminal', '-x', 'python bb.py'])"
python - how can i do a string find on a unicode character that is a variable?,zzz = 'foo'
convert python dictionary `your_data` to json array,"json.dumps(your_data, ensure_ascii=False)"
how to multiply two vector and get a matrix?,"numpy.dot(numpy.array([[1], [2]]), numpy.array([[3, 4]]))"
selecting rows from a numpy ndarray,"test[numpy.logical_or.reduce([(test[:, (1)] == x) for x in wanted])]"
sending binary data over sockets with python,s.send(my_bytes)
array indexing in numpy,"x[(np.arange(x.shape[0]) != 1), :, :]"
how can i convert a python dictionary to a list of tuples?,"[(v, k) for k, v in d.items()]"
get function name as a string in python,print(func.__name__)
python - sum values in dictionary,sum(item['gold'] for item in example_list)
in python how do i convert a single digit number into a double digits string?,"""""""{0:0=2d}"""""".format(a)"
get utc timestamp in python with datetime,return calendar.timegm(dt.utctimetuple())
"replace placeholders in string '{1} {ham} {0} {foo} {1}' with arguments `(10, 20, foo='bar', ham='spam')`","""""""{1} {ham} {0} {foo} {1}"""""".format(10, 20, foo='bar', ham='spam')"
load an html5 canvas into a pil image with django,im = Image.open(tempimg)
decode encodeuricomponent in gae,urllib.parse.unquote(h.path.encode('utf-8')).decode('utf-8')
beautifulsoup - easy way to to obtain html-free contents,return ''.join(soup.findAll(text=True))
extracting just month and year from pandas datetime column (python),df['mnth_yr'] = df['date_column'].apply(lambda x: x.strftime('%B-%Y'))
python regex using re.sub with multiple patterns,"word = re.sub('([aeiou]):(([aeiou][^aeiou]*){3})$', '\\1\\2', word)"
click on the text button 'section-select-all' using selenium python,browser.find_element_by_class_name('section-select-all').click()
how do i sum values in a column that match a given condition using pandas?,df.groupby('a')['b'].sum()[1]
how to capitalize the first letter of each word in a string (python)?,"""""""they're bill's friends from the UK"""""".title()"
python accessing nested json data,print(data['places'][0]['post code'])