text
stringlengths
4
1.08k
set the current working directory to 'c:\\Users\\uname\\desktop\\python',os.chdir('c:\\Users\\uname\\desktop\\python')
set the current working directory to path `path`,os.chdir(path)
get a list `no_integers` of all the items in list `mylist` that are not of type `int`,"no_integers = [x for x in mylist if not isinstance(x, int)]"
match contents of an element to 'Example' in xpath (lxml),"tree.xpath("".//a[text()='Example']"")[0].tag"
"concatenate key/value pairs in dictionary `a` with string ', ' into a single string",""""""", """""".join([(str(k) + ' ' + str(v)) for k, v in list(a.items())])"
"Strip all non-ASCII characters from a unicode string, `\xa3\u20ac\xa3\u20ac`","print(set(re.sub('[\x00-\x7f]', '', '\xa3\u20ac\xa3\u20ac')))"
Get all non-ascii characters in a unicode string `\xa3100 is worth more than \u20ac100`,"print(re.sub('[\x00-\x7f]', '', '\xa3100 is worth more than \u20ac100'))"
"build a dict of key:value pairs from a string representation of a dict, `{'muffin' : 'lolz', 'foo' : 'kitty'}`","ast.literal_eval(""{'muffin' : 'lolz', 'foo' : 'kitty'}"")"
Print string `t` with proper unicode representations,print(t.decode('unicode_escape'))
Normalize string `str` from 'cp1252' code to 'utf-8' code,print(str.encode('cp1252').decode('utf-8').encode('cp1252').decode('utf-8'))
merge lists `list_a` and `list_b` into a list of tuples,"zip(list_a, list_b)"
merge lists `a` and `a` into a list of tuples,"list(zip(a, b))"
convert pandas DataFrame `df` to a dictionary using `id` field as the key,df.set_index('id').to_dict()
"convert pandas dataframe `df` with fields 'id', 'value' to dictionary",df.set_index('id')['value'].to_dict()
remove parentheses and text within it in string `filename`,"re.sub('\\([^)]*\\)', '', filename)"
Check if string 'a b' only contains letters and spaces,"""""""a b"""""".replace(' ', '').isalpha()"
sum each element `x` in list `first` with element `y` at the same index in list `second`.,"[(x + y) for x, y in zip(first, second)]"
sort a python dictionary `a_dict` by element `1` of the value,"sorted(list(a_dict.items()), key=lambda item: item[1][1])"
get index of the biggest 2 values of a list `a`,"sorted(list(range(len(a))), key=lambda i: a[i])[-2:]"
get indexes of the largest `2` values from a list `a` using itemgetter,"zip(*sorted(enumerate(a), key=operator.itemgetter(1)))[0][-2:]"
get the indexes of the largest `2` values from a list of integers `a`,"sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2]"
get index of key 'c' in dictionary `x`,list(x.keys()).index('c')
Print +1 using format '{0:+d}',print('{0:+d}'.format(score))
"remove adjacent duplicate elements from a list `[1, 2, 2, 3, 2, 2, 4]`","[k for k, g in itertools.groupby([1, 2, 2, 3, 2, 2, 4])]"
"split string ""0,1,2"" based on delimiter ','","""""""0,1,2"""""".split(',')"
"convert the string '0,1,2' to a list of integers","[int(x) for x in '0,1,2'.split(',')]"
"convert list of key-value tuples `[('A', 1), ('B', 2), ('C', 3)]` into dictionary","dict([('A', 1), ('B', 2), ('C', 3)])"
save numpy array `x` into text file 'test.txt',"np.savetxt('test.txt', x)"
store the output of command 'ls' in variable `direct_output`,"direct_output = subprocess.check_output('ls', shell=True)"
get all column name of dataframe `df` except for column 'T1_V6',df[df.columns - ['T1_V6']]
get count of values in numpy array `a` that are between values `25` and `100`,((25 < a) & (a < 100)).sum()
Get day name from a datetime object,date.today().strftime('%A')
Jinja parse datetime object `car.date_of_manufacture` to use format pattern `datetime`,{{car.date_of_manufacture | datetime}}
Get the date object `date_of_manufacture` of object `car` in string format '%Y-%m-%d',{{car.date_of_manufacture.strftime('%Y-%m-%d')}}
make a flat list from list of lists `sublist`,[item for sublist in l for item in sublist]
make a flat list from list of lists `list2d`,list(itertools.chain(*list2d))
make a flat list from list of lists `list2d`,list(itertools.chain.from_iterable(list2d))
convert ascii value 'a' to int,ord('a')
replace white spaces in string ' a\n b\n c\nd e' with empty string '',"re.sub('(?m)^[^\\S\\n]+', '', ' a\n b\n c\nd e')"
remove white spaces from all the lines using a regular expression in string 'a\n b\n c',"re.sub('(?m)^\\s+', '', 'a\n b\n c')"
"destruct elements of list `[1, 2, 3]` to variables `a`, `b` and `c`","a, b, c = [1, 2, 3]"
split list `mylist` into a list of lists whose elements have the same first five characters,"[list(v) for k, v in itertools.groupby(mylist, key=lambda x: x[:5])]"
remove all instances of parenthesesis containing text beginning with `as ` from string `line`,"line = re.sub('\\(+as .*?\\) ', '', line)"
skip the newline while printing `line`,print(line.rstrip('\n'))
get index values of pandas dataframe `df` as list,df.index.values.tolist()
check if list `a` is empty,"if (not a):
pass"
check if list `seq` is empty,"if (not seq):
pass"
check if list `li` is empty,"if (len(li) == 0):
pass"
create a list containing the indices of elements greater than 4 in list `a`,"[i for i, v in enumerate(a) if v > 4]"
reverse list `yourdata`,"sorted(yourdata, reverse=True)"
sort list of nested dictionaries `yourdata` in reverse based on values associated with each dictionary's key 'subkey',"sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)"
sort list of nested dictionaries `yourdata` in reverse order of 'key' and 'subkey',"yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)"
remove decimal points in pandas data frame using round,df.round()
Get data from matplotlib plot,gca().get_lines()[n].get_xydata()
get the maximum 2 values per row in array `A`,"A[:, -2:]"
"Get value for ""username"" parameter in GET request in Django","request.GET.get('username', '')"
pretty-print ordered dictionary `o`,pprint(dict(list(o.items())))
Confirm urls in Django properly,"url('^$', include('sms.urls')),"
Configure url in django properly,"url('^', include('sms.urls')),"
get the tuple in list `a_list` that has the largest item in the second index,"max_item = max(a_list, key=operator.itemgetter(1))"
find tuple in list of tuples `a_list` with the largest second element,"max(a_list, key=operator.itemgetter(1))"
resample series `s` into 3 months bins and sum each bin,"s.resample('3M', how='sum')"
"extract elements at indices (1, 2, 5) from a list `a`","[a[i] for i in (1, 2, 5)]"
filter lines from a text file 'textfile' which contain a word 'apple',[line for line in open('textfile') if 'apple' in line]
convert a date string `s` to a datetime object,"datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')"
reading tab-delimited csv file `filename` with pandas on mac,"pandas.read_csv(filename, sep='\t', lineterminator='\r')"
replace only first occurence of string `TEST` from a string `longlongTESTstringTEST`,"'longlongTESTstringTEST'.replace('TEST', '?', 1)"
zip file `pdffile` using its basename as directory name,"archive.write(pdffile, os.path.basename(pdffile))"
create a dictionary of pairs from a list of tuples `myListOfTuples`,dict(x[1:] for x in reversed(myListOfTuples))
subtract elements of list `List1` from elements of list `List2`,"[(x1 - x2) for x1, x2 in zip(List1, List2)]"
check if string `string` starts with a number,string[0].isdigit()
"Check if string `strg` starts with any of the elements in list ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')","strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))"
print script's directory,print(os.path.dirname(os.path.realpath(__file__)))
"split string `text` by the occurrences of regex pattern '(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)'","re.split('(?<=\\?|!|\\.)\\s{0,2}(?=[A-Z]|$)', text)"
Make a scatter plot using unpacked values of list `li`,plt.scatter(*zip(*li))
rearrange tuple of tuples `t`,tuple(zip(*t))
Get average for every three columns in `df` dataframe,"df.groupby(np.arange(len(df.columns)) // 3, axis=1).mean()"
convert a list `L` of ascii values to a string,""""""""""""".join(chr(i) for i in L)"
count the number of pairs in dictionary `d` whose value equal to `chosen_value`,sum(x == chosen_value for x in list(d.values()))
count the number of values in `d` dictionary that are predicate to function `some_condition`,sum(1 for x in list(d.values()) if some_condition(x))
convert double 0.00582811585976 to float,"struct.unpack('f', struct.pack('f', 0.00582811585976))"
convert datetime.date `dt` to utc timestamp,"timestamp = (dt - datetime(1970, 1, 1)).total_seconds()"
sort column `m` in panda dataframe `df`,df.sort('m')
Sort a data `a` in descending order based on the `modified` attribute of elements using lambda function,"a = sorted(a, key=lambda x: x.modified, reverse=True)"
print the truth value of `a`,print(bool(a))
rename `last` row index label in dataframe `df` to `a`,df = df.rename(index={last: 'a'})
Fit Kmeans function to a one-dimensional array `x` by reshaping it to be a multidimensional array of single values,"km.fit(x.reshape(-1, 1))"
Sort a list of strings 'words' such that items starting with 's' come first.,"sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)"
open the login site 'http://somesite.com/adminpanel/index.php' in the browser,webbrowser.open('http://somesite.com/adminpanel/index.php')
"fetch all elements in a dictionary `parent_dict`, falling between two keys 2 and 4","dict((k, v) for k, v in parent_dict.items() if 2 < k < 4)"
fetch all elements in a dictionary 'parent_dict' where the key is between the range of 2 to 4,"dict((k, v) for k, v in parent_dict.items() if k > 2 and k < 4)"
sort two lists `list1` and `list2` together using lambda function,"[list(x) for x in zip(*sorted(zip(list1, list2), key=lambda pair: pair[0]))]"
get the number of values in list `j` that is greater than 5,sum(((i > 5) for i in j))
get the number of values in list `j` that is greater than 5,len([1 for i in j if (i > 5)])
get the number of values in list `j` that is greater than `i`,"j = np.array(j)
sum((j > i))"
"zip list `a`, `b`, `c` into a list of tuples","[(x + tuple(y)) for x, y in zip(zip(a, b), c)]"