Dividing the list in Python and print the combinations - python-3.x

If i have a list in python, i want to divide the list into sub lists of some size 's' and then produce all the combinations of the sub_lists of size 2.
E.g :
Input: List = ['1','2','3','4']
sub-list size s = 3
My Output should be :
Sub-List-1 = ['1','2','3']
Combinations-1 = [('1','2'),('1','3'),('2','3')]
Sub-List-2 = ['2','3','4']
Combinations-2 = [('2','3'),('2','4'),('3','4')]
I tried this, but it did not work:
combination_list = []
while (myList):
sub_list = []
sub_list.append(myList[:s])
myList = myList[s:]
combination_list.append(combinations(sub_list, 2))
My Logic is :
Create an empty List for Combination
While my original List is not empty
Create an empty list for Sub lists
Append the s items to the sub lists
Remove s items from my original List(the items present in my sub list)
Produce the combinations of elements in my sub Lists
But i am not getting an expected output. Could someone help me with this please?

you can try this, i hope it helps
import itertools
mylist = ['1','2','3','4']
ls =[]
for i in range(0,int(len(mylist)/2)):
ls.append([mylist[i],mylist[i+1],mylist[i+2]])
print(len(ls)) /just getting the length to know how many sublist you have
sub1 = ls[0]
sub2 = ls[1]
comb1 =[]
comb2 =[]
//using itertools
comb1 = list(itertools.combinations(sub1,2))
comb2 = list(itertools.combinations(sub2,2))
print("combinations")
print(comb1)
print(comb2)
// if you want to use any import then you can use for-loop to do the
logic
ncomb = []
for i in range(len(sub1)-1):
for a in range(i,len(sub1)-1):
ncomb.append((sub1[i],sub1[a+1]))
print(ncomb) // output the same [('1', '2'), ('1', '3'), ('2', '3')]
//or better with List comprehension
lsize = len(sub1)
listcomp = [(sub1[x],sub1[y+1]) for x in range(lsize-1) for y in range(x,lsize-1)]
print(listcomp) // output the same [('1', '2'), ('1', '3'), ('2', '3')]
combinations
[('1', '2'), ('1', '3'), ('2', '3')]
[('2', '3'), ('2','4'), ('3', '4')]

result_list = []
combination_list = []
for i in range(len(myList)-s+1):
result_list.clear()
for j in range(i,i+s):
result_list.append(myList[j])
for i in combinations(result_list, 2):
combination_list.append((i[0],i[1]))
I got what is expected with the above piece of code!!But if you think it can be improved or there's something wrong with the code, please let me know!!

Related

How to get unique values in nested list along single column?

I need to extract only unique sublists based on first element from a nested list. For e.g.
in = [['a','b'], ['a','d'], ['e','f'], ['g','h'], ['e','i']]
out = [['a','b'], ['e','f'], ['g','h']]
My method is two break list into two lists and check for elements individually.
lis = [['a','b'], ['a','d'], ['e','f'], ['g','h']]
lisa = []
lisb = []
for i in lis:
if i[0] not in lisa:
lisa.append(i[0])
lisb.append(i[1])
out = []
for i in range(len(lisa)):
temp = [lisa[i],lisb[i]]
out.append(temp)
This is an expensive operation when dealing with list with 10,00,000+ sublists. Is there a better method?
Use memory-efficient generator function with an auziliary set object to filter items on the first unique subelement (take first unique):
def gen_take_first(s):
seen = set()
for sub_l in s:
if sub_l[0] not in seen:
seen.add(sub_l[0])
yield sub_l
inp = [['a','b'], ['a','d'], ['e','f'], ['g','h'], ['e','i']]
out = list(gen_take_first(inp))
print(out)
[['a', 'b'], ['e', 'f'], ['g', 'h']]

Join lists as a result of append in Loop

I have lists as results of an append, and I want to join the lists:
for info_api in data:
unit_id = info_api['unitId']
porcentagem = round(info_api['similarityScore'] * 100)
apto = info_api['unitNumber']
final_info_api = [apto, unit_id, porcentagem]
final_data.append(final_info_api)
print("Result:", final_data)
# output:
# Result: [['5', 140382, 62], ['55', 140413, 61]]
# Result: [['105', 140442, 57], ['51', 140410, 56]]
What I want is to join the lists that came from the append:
Result: ['5', 140382, 62], ['55', 140413, 61],['105', 140442, 57], ['51', 140410, 56]
Why do you use append? You could use extend directly.
Otherwise if you need to keep final_data that way, you can flatten it for example with sum(final_data, [])

Converting string into list of every two numbers in string

A string = 1 2 3 4
Program should return = [[1,2],[3,4]]
in python
I want the string to be converted into a list of every two element from string
You could go for something very simple such as:
s = "10 2 3 4 5 6 7 8"
l = []
i = 0
list_split_str = s.split() # splitting the string according to spaces
while i < len(s) - 1:
l.append([s[i], s[i + 1]])
i += 2
This should output:
[['10', '2'], ['3', '4'], ['5', '6'], ['7', '8']]
You could also do something a little more complex like this in a two-liner:
list_split = s.split() # stripping spaces from the string
l = [[a, b] for a, b in zip(list_split[0::2], list_split[1::2])]
The slice here means that the first list starts at index zero and has a step of two and so is equal to [10, 3, 5, ...]. The second means it starts at index 1 and has a step of two and so is equal to [2, 4, 6, ...]. So we iterate over the first list for the values of a and the second for those of b.
zip returns a list of tuples of the elements of each list. In this case, [('10', '2'), ('3', '4'), ('5', '6'), ...]. It allows us to group the elements of the lists two by two and iterate over them as such.
This also works on lists with odd lengths.
For example, with s = "10 2 3 4 5 6 7 ", the above code would output:
[['10', '2'], ['3', '4'], ['5', '6']]
disregarding the 7 since it doesn't have a buddy.
here is the solution if the numbers exact length is divisible by 2
def every_two_number(number_string):
num = number_string.split(' ')
templist = []
if len(num) % 2 == 0:
for i in range(0,len(num),2):
templist.append([int(num[i]),int(num[i+1])])
return templist
print(every_two_number('1 2 3 4'))
you can remove the if condition and enclosed the code in try and except if you want your string to still be convert even if the number of your list is not divisible by 2
def every_two_number(number_string):
num = number_string.split(' ')
templist = []
try:
for i in range(0,len(num),2):
templist.append([int(num[i]),int(num[i+1])])
except:
pass
return templist
print(every_two_number('1 2 3 4 5'))

How to add a lots of list items in a different list in Python

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]

How to Convert list of string to tuple in python

I am facing a problem to convert from List to tuple. For example i have lists like this
['1', '9']
['2']
['3']
['4']
I want output like this
[(1,9),(2),(3),(4)]
Kindly help me. I am not getting any way.
If you have a list 'l' then you can call the builtin function 'tuple' on it to convert to a tuple
l = [1,2]
tup = tuple(l)
print tup # (1,2)
if you have a list of list l = [['1', '9'], ['2'], ['3'], ['4']]
you can do :
l = [['1', '9'], ['2'], ['3'], ['4']]
tups = map(lambda x: tuple(x), l)
print tups # [(1,9),(2),(3),(4)]

Resources