This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Given a list of lists t | |
flat_list = [item for sublist in t for item in sublist] | |
flat_list = [] | |
for sublist in t: | |
for item in sublist: | |
flat_list.append(item) | |
# OR | |
flatten = lambda t: [item for sublist in t for item in sublist] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Given a list [[1,2,3], [4,5,6], [7,8,9]] | |
{words[0]:words[1:] for words in lst} | |
#result | |
#{1: [2, 3], 4: [5, 6], 7: [8, 9]} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test_list = [{'gfg' : [1, 5, 6, 7], 'good' : [9, 6, 2, 10], 'CS' : [4, 5, 6]}, | |
{'gfg' : [5, 6, 7, 8], 'CS' : [5, 7, 10]}, | |
{'gfg' : [7, 5], 'best' : [5, 7]}] | |
# Concatenate Similar Key values | |
# Using loop | |
res = dict() | |
for dict in test_list: | |
for list in dict: | |
if list in res: |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import groupby | |
test_list = ['geek_1', 'coder_2', 'geek_4', 'coder_3', 'pro_3'] | |
test_list.sort() | |
res = [list(i) for j, i in groupby(test_list, | |
lambda a: a.split('_')[0])] | |
#The original list is : [‘coder_2’, ‘coder_3’, ‘geek_1’, ‘geek_4’, ‘pro_3’] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Another way to populate a dict when using enumerate | |
my_dict = {} | |
my_string = 'Something' | |
for i, my_dict[i] in enumerate(my_string): | |
pass | |
# Output: | |
# {0: 'S', 1: 'o', 2: 'm', 3: 'e', 4: 't', 5: 'h', 6: 'i', 7: 'n', 8: 'g'} |
OlderNewer