text
stringlengths
4
1.08k
sort a list of tuples `b` by third item in the tuple,b.sort(key=lambda x: x[1][2])
get the highest element in absolute value in a numpy matrix `x`,"max(x.min(), x.max(), key=abs)"
get all urls within text `s`,"re.findall('""(http.*?)""', s, re.MULTILINE | re.DOTALL)"
sum elements at the same index in list `data`,[[sum(item) for item in zip(*items)] for items in zip(*data)]
How to convert a list of multiple integers into a single integer?,"sum(d * 10 ** i for i, d in enumerate(x[::-1]))"
How to convert a list of multiple integers into a single integer?,"r = int(''.join(map(str, x)))"
how to convert a datetime string back to datetime object?,"datetime.strptime('2010-11-13 10:33:54.227806', '%Y-%m-%d %H:%M:%S.%f')"
Averaging the values in a dictionary based on the key,"[(i, sum(j) / len(j)) for i, j in list(d.items())]"
zip lists in python,"zip([1, 2], [3, 4])"
Prepend the same string to all items in a list,['hello{0}'.format(i) for i in a]
regex for repeating words in a string in Python,"re.sub('(?<!\\S)((\\S+)(?:\\s+\\2))(?:\\s+\\2)+(?!\\S)', '\\1', s)"
Normalizing a pandas DataFrame by row,"df.div(df.sum(axis=1), axis=0)"
swap values in a tuple/list inside a list in python?,"map(lambda t: (t[1], t[0]), mylist)"
swap values in a tuple/list inside a list in python?,"[(t[1], t[0]) for t in mylist]"
Find next sibling element in Python Selenium?,"driver.find_element_by_xpath(""//p[@id, 'one']/following-sibling::p"")"
Python splitting string by parentheses,"re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|""[^""]*""|\\S+', strs)"
What's the most memory efficient way to generate the combinations of a set in python?,"print(list(itertools.combinations({1, 2, 3, 4}, 3)))"
Add Multiple Columns to Pandas Dataframe from Function,"df[['hour', 'weekday', 'weeknum']] = df.apply(lambdafunc, axis=1)"
BeautifulSoup - search by text inside a tag,"soup.find_all('a', string='Elsie')"
"How do I turn a python datetime into a string, with readable format date?","my_datetime.strftime('%B %d, %Y')"
Parse string to int when string contains a number + extra characters,int(''.join(c for c in s if c.isdigit()))
adding new key inside a new key and assigning value in python dictionary,dic['Test'].update({'class': {'section': 5}})
Transforming the string representation of a dictionary into a real dictionary,"dict(map(int, x.split(':')) for x in s.split(','))"
How to select element with Selenium Python xpath,"driver.find_element_by_xpath(""//div[@id='a']//a[@class='click']"")"
Find matching rows in 2 dimensional numpy array,"np.where((vals == (0, 1)).all(axis=1))"
How to delete a record in Django models?,SomeModel.objects.filter(id=id).delete()
python convert list to dictionary,"dict([['two', 2], ['one', 1]])"
python convert list to dictionary,"dict(zip(l[::2], l[1::2]))"
how to set global const variables in python,GRAVITY = 9.8
"How to use regular expression to separate numbers and characters in strings like ""30M1000N20M""","re.findall('(([0-9]+)([A-Z]))', '20M10000N80M')"
"How to use regular expression to separate numbers and characters in strings like ""30M1000N20M""","re.findall('([0-9]+|[A-Z])', '20M10000N80M')"
"How to use regular expression to separate numbers and characters in strings like ""30M1000N20M""","re.findall('([0-9]+)([A-Z])', '20M10000N80M')"
"Extracting words from a string, removing punctuation and returning a list with separated words in Python","re.compile('\\w+').findall('Hello world, my name is...James the 2nd!')"
Convert string into datetime.time object,"datetime.datetime.strptime('03:55', '%H:%M').time()"
Python Requests getting SSLerror,"requests.get('https://www.reporo.com/', verify=False)"
removing data from a numpy.array,a[a != 0]
Map two lists into a dictionary in Python,"new_dict = {k: v for k, v in zip(keys, values)}"
Map two lists into a dictionary in Python,"dict((k, v) for k, v in zip(keys, values))"
Map two lists into a dictionary in Python,"dict([(k, v) for k, v in zip(keys, values)])"
Get the string within brackets in Python,"m = re.search('\\[(\\w+)\\]', s)"
"Python server ""Only one usage of each socket address is normally permitted""","s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)"
How do i add two lists' elements into one list?,"list3 = [(a + b) for a, b in zip(list1, list2)]"
Python - Converting Hex to INT/CHAR,[ord(c) for c in s.decode('hex')]
How to sort in decreasing value first then increasing in second value,"print(sorted(student_tuples, key=lambda t: (-t[2], t[0])))"
Repeating elements in list comprehension,"[y for x in range(3) for y in [x, x]]"
"Doc, rtf and txt reader in python",txt = open('file.txt').read()
How do you divide each element in a list by an int?,myList[:] = [(x / myInt) for x in myList]
python: dots in the name of variable in a format string,"""""""Name: {0[person.name]}"""""".format({'person.name': 'Joe'})"
How to replace the white space in a string in a pandas dataframe?,"df.replace(' ', '_', regex=True)"
Python: most efficient way to convert date to datetime,"datetime.datetime.combine(my_date, datetime.time.min)"
Tuple to string,tst2 = str(tst)
get file creation & modification date/times in,time.ctime(os.path.getmtime(file))
get file creation & modification date/times in,time.ctime(os.path.getctime(file))
get file creation & modification date/times in,t = os.path.getmtime(filename)
get file creation & modification date/times in,os.path.getmtime(path)
get file creation & modification date/times in,print(('last modified: %s' % time.ctime(os.path.getmtime(file))))
get file creation & modification date/times in,print(('created: %s' % time.ctime(os.path.getctime(file))))
get file creation & modification date/times in,return os.path.getctime(path_to_file)
How to Close a program using python?,os.system('TASKKILL /F /IM firefox.exe')
Is there a generator version of `string.split()` in Python?,"return (x.group(0) for x in re.finditer(""[A-Za-z']+"", string))"
Using Python String Formatting with Lists,""""""", """""".join(['%.2f'] * len(x))"
How to use regex with optional characters in python?,"print(re.match('(\\d+(\\.\\d+)?)', '3434.35353').group(1))"
How to remove parentheses and all data within using Pandas/Python?,"df['name'].str.replace('\\(.*\\)', '')"
Python: filter list of list with another list,result = [x for x in list_a if x[0] in list_b]
Generate all possible strings from a list of token,"print([''.join(a) for a in combinations(['hel', 'lo', 'bye'], 2)])"
python how to search an item in a nested list,[x for x in li if 'ar' in x[2]]
Python - How to sort a list of lists by the fourth element in each list?,unsorted_list.sort(key=lambda x: x[3])
Python logging typeerror,logging.info('test')
How to make several plots on a single page using matplotlib?,"fig.add_subplot(1, 1, 1)"
Sort a Python dictionary by value,"sorted(list(x.items()), key=operator.itemgetter(1))"
Sort a Python dictionary by value,"sorted(dict1, key=dict1.get)"
Sort a Python dictionary by value,"sorted(d, key=d.get, reverse=True)"
Sort a Python dictionary by value,"sorted(list(d.items()), key=(lambda x: x[1]))"
Numpy elementwise product of 3d array,"np.einsum('ijk,ikl->ijl', A, B)"
print variable and a string in python,print('I have: {0.price}'.format(card))
How can I add a comment to a YAML file in Python,f.write('# Data for Class A\n')
How do I move the last item in a list to the front in python?,a = a[-1:] + a[:-1]
python - convert datetime to varchar/string,datetimevariable.strftime('%Y-%m-%d')
What's the most pythonic way of normalizing lineends in a string?,"mixed.replace('\r\n', '\n').replace('\r', '\n')"
How to find the real user home directory using python?,os.path.expanduser('~user')
"In Python, how do I index a list with another list?",T = [L[i] for i in Idx]
Iterate through words of a file in Python,words = open('myfile').read().split()
Summing 2nd list items in a list of lists of lists,[[sum([x[1] for x in i])] for i in data]
Summing 2nd list items in a list of lists of lists,[sum([x[1] for x in i]) for i in data]
Django order by highest number of likes,Article.objects.annotate(like_count=Count('likes')).order_by('-like_count')
How to convert datetime.date.today() to UTC time?,today = datetime.datetime.utcnow().date()
How to perform element-wise multiplication of two lists in Python?,"[(a * b) for a, b in zip(lista, listb)]"
Capturing emoticons using regular expression in python,"re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', s)"
Capturing emoticons using regular expression in python,"re.match('[:;][)(](?![)(])', str)"
List of objects to JSON with Python,json_string = json.dumps([ob.__dict__ for ob in list_name])
List of zeros in python,listofzeros = [0] * n
python: how to convert a string to utf-8,"stringnamehere.decode('utf-8', 'ignore')"
Python regex - Ignore parenthesis as indexing?,"re.findall('((?:A|B|C)D)', 'BDE')"
Python dict how to create key or append an element to key?,"dic.setdefault(key, []).append(value)"
Finding the minimum value in a numpy array and the corresponding values for the rest of that array's row,"a[np.argmin(a[:, (1)])]"
"Python ""extend"" for a dictionary",a.update(b)
Removing key values pairs from a list of dictionaries,"[{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]"
Simple way to create matrix of random numbers,"numpy.random.random((3, 3))"
Make new column in Panda dataframe by adding values from other columns,df['C'] = df['A'] + df['B']