I have a list name list1:
list1 = [['DC1', 'C4'], ['DC1', 'C5'], ['DC3', 'C1'], ['DC3', 'C2'], ['DC3', 'C3']]
I want to make two new lists:
list1_1 = ['DC1', 'C4', 'C5']
list1_2 = ['DC3', 'C1', 'C2', 'C3']
can anyone please show me how to do?
thank you.
this can solve your problem. note: this is not an optimized one
yourlist = [['DC1', 'C4'], ['DC1', 'C5'], ['DC3', 'C1'], ['DC3', 'C2'], ['DC3', 'C3']]
temp_dict = {}
for i in yourlist:
if i[0] not in temp_dict:
temp_dict.update({i[0]:[i[1]]})
else:
temp_dict[i[0]].append(i[1])
final_list =[]
for i,j in temp_dict.items():
temp_list =[i]
for k in j:
temp_list.append(k)
final_list.append(temp_list)
list1_1 = final_list[0]
list1_2 = final_list[1]
Output:
list1_1
['DC1', 'C4', 'C5']
list1_2
['DC3', 'C1', 'C2', 'C3']
Building on Tamil Selvan's answer, but using a defaultdict for simplicity and list concatenation instead of appends for the big list.
from collections import defaultdict
list1 = [['DC1', 'C4'], ['DC1', 'C5'], ['DC3', 'C1'], ['DC3', 'C2'], ['DC3', 'C3']]
# First we create a dict containing the left terms as keys and the right terms as values.
d = defaultdict(list)
for (key, value) in list1:
d[key].append(value)
print(d)
# {'DC1': ['C4', 'C5'],
# 'DC3': ['C1', 'C2', 'C3']}
# Then for each key, we create a list of values with the key as first item.
lists = []
for key, values in d.items():
sublist = [key, *values]
lists.append(sublist)
print(lists)
# [['DC1', 'C4', 'C5'],
# ['DC3', 'C1', 'C2', 'C3']]
# Finally, you can easily take the sublist that you want.
list1_1, list1_2 = lists
Related
I am trying to convert list elements of a given list to list value of another list. Here is an example:
list1 = ['apple', 'tomato', 'milk', 'beans', 'mango']
list2 = [{0,4}, {1,3}, 2]
result = []
expected output:
[{'apple', 'banana'}, {'tomato', 'beans'}, 'milk']
I am trying to use the below code, but it does not work:
for i in list2:
result.append(list1[i])
Assuming list2 will only contain set, list, or int. This would be my approach.
list1 = ['apple', 'tomato', 'milk', 'beans', 'mango']
list2 = [{0,4}, {1,3}, 2]
result = []
# [{'apple', 'banana'}, {'tomato', 'beans'}, 'milk']
for x in list2:
temp_lst = []
if type(x) in [set, list]:
new_set = set()
for y in x:
new_set.add(list1[y])
temp_lst.append(new_set)
else:
temp_lst.append(list1[x])
result.extend(temp_lst)
print(result)
list1 = [99,55]
dict1 = {'k1':[],'k2':[]}
for num in list1:
if num > 77:
dict1['k1'].append(num)
else:
dict1['k2'].append(num)
print(dict1)
{'k1':[99],'k2':[55]}
But when I replaced dict1 = {'k1':[],'k2':[]} to {}.fromkeys(['k1','k2'],[]) , the result became {'k1': [99, 55], 'k2': [99, 55]}
why this happens? I really have no idea.
This happens because you are passing the same list object to both keys. This is the same situation as when you create an alias for a variable:
a = []
b = a
a.append(55)
b.append(99)
print(b)
prints [55, 99] because it is the same list instance.
If you want to make it more concise from a list of keys to initialize with empty list, you can do this:
dict1 = {k: [] for k in ('k1', 'k2')}
This will create a new list instance for every key.
Alternatively, you can use defaultdict
from collections import defaultdict
list1 = [99,55]
dict1 = defaultdict(list)
for num in list1:
if num > 77:
dict1['k1'].append(num)
else:
dict1['k2'].append(num)
print(dict1)
Also works.
The fromKeys() can also be supplied with a mutable object as the default value.
if we append value in the original list, the append takes place in all the values of keys.
example:
list1 = ['a', 'b', 'c', 'd']
list2 = ['SALIO']
dict1 = dict.fromkeys(list1, list2)
print(dict1)
output:
{'a': ['SALIO'], 'b': ['SALIO'], 'c': ['SALIO'], 'd': ['SALIO']}
then you can use this:
list1 = ['k1', 'k2']
dict1 = {'k1':[],'k2':[]}
list2 =[99,55]
for num in list2:
if num > 77:
a = ['k1']
dict1 = dict.fromkeys(a, [num])
else:
b = ['k2']
dict2 = dict.fromkeys(b,[num] )
res = {**dict1, **dict2}
print(res)
output:
{'k1': [99], 'k2': [55]}
You can also use the python code to merge dict code:
this function:
def Merge(dict1, dict2):
return(dict2.update(dict1))
then:
print(Merge(dict1, dict2)) #This return None
print(dict2) # changes made in dict2
I am trying to create a method that sorts a list of variables into clumps of size four, with the same characters grouped together and in the same order as they are given. You may assume the only given characters are a, b, and c. For example, here I would like to sort myInitialList.
myInitialList = ['b1', 'c1', 'b2', 'c2', 'c3', 'b3', 'c4', 'a1', 'b4', 'b5', 'a2', 'c5', 'a3', 'a4', 'a5', 'c6', 'a6', 'a7', 'a8','a9']
endList = clumpsSize4(myInitialList)
print(endList)
This should output the result:
['a1','a2','a3','a4','b1','b2','b3','b4','c1','c2','c3','c4','a5','a6','a7','a8','b5','c5','c6','a9']
How do I write the clumpsSize4 method?
This is not the most efficient, but here is my attempt. Sort the input. Have one default dict groupNums which links a letter to the current number clump it is on. Have another default dict groups which contains the actual clumps. Sort the groups at the end, iterate over them and join:
from collections import defaultdict
def clump(l, size=4):
groups = defaultdict(list)
groupNums = defaultdict(int)
l = sorted(l)
for i in l:
letter = i[0]
key = str(groupNums[letter]) + letter
groups[key].append(i)
if len(groups[key]) == size:
groupNums[letter] += 1
result = []
for _, g in sorted(groups.items()):
result += g
return result
I have a string
s = 'A;B;C1,C2,C3;D'
I want to split this string in a 2D list, so the result would be:
alist = [['A'], ['B'], ['C1', 'C2', 'C3'], ['D']]
I can't do that with
'A;B;C1,C2,C3;D'.split(';').split(',')
because AttributeError: 'list' object has no attribute 'split'
Is there an easy way to fill this 2d list at once?
You could use a list comprehension
>>> res = [s1.split(',') for s1 in s.split(';')]
>>> res
[['A'], ['B'], ['C1', 'C2', 'C3'], ['D']]
I was creating a list python file. There I created a lot of list and adding new items and lists everyday. I wanted to create a list that will have all the items of previous lists automatically. What should I do?
list_1=['1','one','first',etc...]
list_2=['2','two', 'second', '2nd', etc]
.
.
list_x=['x', 'cross']
all_list=list_1+list_2+....+list_x+... #this will update automatically
How to do it?
This problem can actually be solved by a more adapted choice of data structure. If some items are related, they should be stored together inside a container such as a dict or a list of lists. Doing so will both make them easier to access and will clean your scope.
all_lists = {
'1': ['1', 'one', 'first', ...],
'2': ['2', 'two', 'second', ...],
...: ...,
'x': ['x', 'cross']
}
You can now access a specific list...
list_1 = all_lists['1']
... check if an item is inside the lists.
if any(item in lst for lst in all_lists.values())
print('The item is all_lists')
... or iterate over all lists with a nested loop.
for lst in all_lists.values():
for item in lst:
print(item)
If you are going to collect all lists, this code can do the job.
def generate_list():
l = [globals()[name] for name in globals().keys() if name.startswith('list_')]
return [item for sublist in l for item in sublist]
list_1 = [1]
list_2 = [2]
list_3 = [3]
print(generate_list())
result: [1, 2, 3]