text stringlengths 4 1.08k |
|---|
how to get the original variable name of variable passed to a function,"['e', '1000', 'c']" |
more efficient way to look up dictionary values whose keys start with same prefix,result = [d[key] for key in d if key.startswith(query)] |
"create list `done` containing permutations of each element in list `[a, b, c, d]` with variable `x` as tuples","done = [(el, x) for el in [a, b, c, d]]" |
decode url `url` from utf-16 code to utf-8 code,urllib.parse.unquote(url).decode('utf8') |
shape of array python,"m[:, (0)].reshape(5, 1).shape" |
how to change the window title in pyside?,self.show() |
how to find list intersection?,c = [x for x in b if x in _auxset] |
convert string `x' to dictionary splitted by `=` using list comprehension,dict([x.split('=') for x in s.split()]) |
dictionary within dictionary in python 3,result = copy.deepcopy(old_dict) if old_dict is not None else {} |
lambda function that adds two operands,"lambda x, y: x + y" |
how to assign items inside a model object with django?,my_model.save() |
how to write/read a pandas dataframe with multiindex from/to an ascii file?,"df.to_csv('mydf.tsv', sep='\t')" |
is there a more pythonic way to populate a this list?,"[2, 4, 6, 8]" |
how to check if any value of a column is in a range in pandas?,df[(x <= df['columnX']) & (df['columnX'] <= y)] |
python: flatten to a list of lists but no more,"[[1, 2, 3], ['a', 'b', 'c']]" |
sort list of strings `xs` by the length of string,xs.sort(key=lambda s: len(s)) |
how to implement a dynamic programming algorithms to tsp in python?,A = [[(0) for i in range(n)] for j in range(2 ** n)] |
how to keep a python script output window open?,input() |
comparing two dictionaries in python,"zip(iter(x.items()), iter(y.items()))" |
sort dictionary `dictionary` in ascending order by its values,"sorted(list(dictionary.items()), key=operator.itemgetter(1))" |
how to parse malformed html in python,print(soup.prettify()) |
python convert decimal to hex,hex(d).split('x')[1] |
python: string formatting a regex string that uses both '%' and '{' as characters,"""""""([0-9]{{1,3}}[%])([{0}]?)"""""".format(config.SERIES)" |
convert date string `s` in format pattern '%d/%m/%y' into a timestamp,"time.mktime(datetime.datetime.strptime(s, '%d/%m/%Y').timetuple())" |
getting every possible combination in a list,"list(itertools.combinations([1, 2, 3, 4, 5, 6], 2))" |
how to check if something exists in a postgresql database using django?,"Entry.objects.filter(name='name', title='title').exists()" |
how to derive the week start for a given (iso) weeknumber / year in python,"datetime.datetime.strptime('2011, 4, 0', '%Y, %U, %w')" |
sort dictionary `d` by key,od = collections.OrderedDict(sorted(d.items())) |
is there a python builtin to create tuples from multiple lists?,"zip([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14])" |
python regular expression match,"print(re.sub('[.]', '', re.search('(?<=//).*?(?=/)', str).group(0)))" |
making a list of evenly spaced numbers in a certain range in python,"np.linspace(0, 5, 10, endpoint=False)" |
removing rows in a pandas dataframe where the row contains a string present in a list?,df[~df.From.str.contains('|'.join(ignorethese))] |
python - remove and replace printed items,sys.stdout.write('\x1b[K') |
simple python udp server: trouble receiving packets from clients other than localhost,"sock.bind(('', UDP_PORT))" |
format string - spaces between every three digit,"""""""{:,}"""""".format(12345678.46)" |
how to retrieve table names in a mysql database with python and mysqldb?,tables = cursor.fetchall() |
subprocess.popen with a unicode path,"subprocess.call(['start', 'avi\xf3n.mp3'.encode('latin1')], shell=True)" |
python pandas: plot histogram of dates?,df.groupby(df.date.dt.month).count().plot(kind='bar') |
selenium webdriver - nosuchelementexceptions,driver.implicitly_wait(60) |
get list of n next values of a generator `it`,"list(itertools.islice(it, 0, n, 1))" |
python: getting rid of \u200b from a string using regular expressions,'used\u200b'.strip('\u200b') |
change current working directory to directory 'chapter3',os.chdir('chapter3') |
get all digits in a string `s` after a '[' character,"re.findall('\\d+(?=[^[]+$)', s)" |
how to set the current working directory in python?,os.chdir('c:\\Users\\uname\\desktop\\python') |
efficiently applying a function to a grouped pandas dataframe in parallel,"df.set_index('key', inplace=True)" |
convert generator object to a dictionary,"dict((i, i * 2) for i in range(10))" |
enclose numbers in quotes in a string `this is number 1 and this is number 22`,"re.sub('(\\d+)', '""\\1""', 'This is number 1 and this is number 22')" |
fastest way to uniqify a list in python,"set([a, b, c, a])" |
"can i do a ""string contains x"" with a percentage accuracy in python?","['uncorn', 'corny', 'unicycle']" |
check if string contains a certain amount of words of another string,"zip(string, string[1:], string[2:])" |
iterate backwards from 10 to 0,"range(10, 0, -1)" |
get the maximum string length in nested list `i`,"len(max(i, key=len))" |
how to print a unicode string in python in windows console,print('\u5f15\u8d77\u7684\u6216') |
django order by highest number of likes,Article.objects.annotate(like_count=Count('likes')).order_by('-like_count') |
parse string to int when string contains a number + extra characters,int(''.join(c for c in s if c.isdigit())) |
how to programmatically tell celery to send all log messages to stdout or stderr?,my_handler = logging.StreamHandler(sys.stdout) |
python - regex search and findall,"regex = re.compile('((\\d+,?)+)')" |
how to select element with selenium python xpath,"driver.find_element_by_xpath(""//div[@id='a']//a[@class='click']"")" |
converting a dict into a list,"['We', 'Love', 'Your', 'Dict']" |
how can i make multiple empty arrays in python?,listOfLists = [[] for i in range(N)] |
python numpy: cannot convert datetime64[ns] to datetime64[d] (to use with numba),testf(df['month_15'].astype('datetime64[D]').values) |
how to split a string into integers in python?,"""""""42 0"""""".split()" |
sort dict `data` by value,"sorted(data, key=data.get)" |
can i run a python script as a service?,sys.exit(0) |
python script that prints its source,print(f.read()) |
using regular expression to split string in python,[match.group(0) for match in pattern.finditer('44442(2)2(2)44')] |
how to get n elements of a list not contained in another one?,"set([3, 5, 7, 9])" |
sort the list of tuples `lst` by the sum of every value except the first and by the first value in reverse order,"sorted(lst, key=lambda x: (sum(x[1:]), x[0]), reverse=True)" |
python selenium click on button,driver.find_element_by_css_selector('.button.c_button.s_button').click() |
"find rows of 2d array in 3d numpy array 'arr' if the row has value '[[0, 3], [3, 0]]'","np.argwhere(np.all(arr == [[0, 3], [3, 0]], axis=(1, 2)))" |
numpy: find the euclidean distance between two 3-d arrays,"np.linalg.norm(A - B, axis=-1)" |
convert utf-8 with bom to utf-8 with no bom in python,return s.decode('latin-1') |
find button that is in li class `next` and assign it to variable `next`,next = driver.find_element_by_css_selector('li.next>a') |
how to rotate a qpushbutton?,self.layout.addWidget(self.button) |
python pandas: convert rows as column headers,"medals.reindex_axis(['Gold', 'Silver', 'Bronze'], axis=1)" |
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)" |
how to find the index of a value in 2d array in python?,np.where(a == 1) |
numpy array indexing,"array([0.63143784, 0.93852927, 0.0026815, 0.66263594, 0.2603184])" |
store the output of command 'ls' in variable `direct_output`,"direct_output = subprocess.check_output('ls', shell=True)" |
generate a waveform image from an audio file,matplotlib.pyplot.plot(raw_audio_data) |
format string by binary list,"['-', 't', '-', 'c', '-', 'over', '----']" |
what's the proper way to write comparator as key in python 3 for sorting?,"print(sorted(l, key=my_key))" |
delete the first element in subview of a matrix,"b = np.delete(a, i, axis=0)" |
persistent memoization in python,time.sleep(1) |
beautifulsoup get value associated with attribute 'content' where attribute 'name' is equal to 'city' in tag 'meta' in html parsed string `soup`,"soup.find('meta', {'name': 'City'})['content']" |
how to teach beginners reversing a string in python?,'dammit im mad'[::-1] == 'dammit im mad' |
function to check if a string is a number,isdigit() |
create list of dictionary python,"[{'data': 0}, {'data': 1}, {'data': 2}]" |
how to convert string to class sub-attribute with python,"getattr(getattr(getattr(f, 'bar'), 'baz'), 'quux')" |
sort a list of strings 'mylist'.,mylist.sort() |
assign an array of floats in range from 0 to 100 to a variable `values`,"values = np.array([i for i in range(100)], dtype=np.float64)" |
how to add a variable into my re.compile expression,regex2 = re.compile('.*({}).*'.format(what2look4)) |
print float `a` with two decimal points,"print(('%.2f' % round(a, 2)))" |
how to check if a value is in the list in selection from pandas data frame?,"df_new[df_new['l_ext'].isin([31, 22, 30, 25, 64])]" |
merge and sort a list using merge sort,"all_lst = [[2, 7, 10], [0, 4, 6], [1, 3, 11]]" |
python regex to match string excluding word,"re.search('^((?!bantime|(invokername=server)).)*$', s, re.M).group()" |
how to assert that a method is decorated with python unittest?,"assert getattr(MyClass.my_method, '__wrapped__').__name__ == 'my_method'" |
loop through `mylist` with step 2,"for i in mylist[::2]: |
pass" |
normalize line ends in a string 'mixed',"mixed.replace('\r\n', '\n').replace('\r', '\n')" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.