Join two lists into one row-wise - python

I have two lists and need to join them by rows. The output looks like list3 (below). Actually there aren't any commas between the bracketed pairs. I've tried a few different things and can't figure this out.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
my desired output is: list3 = [[1 4], [2 5], [3 6]]

Use zip
[[i, j] for i,j in zip(list1 , list1 )]
[[1, 4], [2, 5], [3, 6]]

I am not sure if you want the final list to be list of lists or not but I will assume you do,
list1 = [1, 2, 3]
list2 = [4, 5, 6]
res = [[*np.asarray([list1, list2])[:,i]] for i in range(3)]
res = [[1, 4], [2, 5], [3, 6]]

Related

How to iterate over a list of lists of integers?

As far as I know this question hasn't been asked.
If I have two lists like so:
a_list = [[1,2], [5,6], [7,8]]
b_list = [3, 4]
How can I iterate over them while checking if the values of b_list fit the ascending order of the numbers in a_list? in this case b_list fits between [1, 2] and [5, 6] and should be appending in that spot. How would this be done in python?
When I use a for loop it tells me:
"TypeError: 'int' object is not subscriptable"
I used this code:
for sub_lst in a_lst:
for lst in sub_lst:
You can simply append b to a then sort all elements:
>>> a_list = [[1, 2], [5, 6], [7, 8]]
>>> b_list = [3, 4]
>>> sorted(a_list + [b_list])
[[1, 2], [3, 4], [5, 6], [7, 8]]
If you want to stick with what you have (with the for loop) do
for index, sub_list in enumerate(a_list):
if sub_list[0] < b_list[0]:
continue
elif sub_list[0] == b_list[0] and sub_list[1] < b_list[1]:
continue
else:
a_list.insert(index, b_list)
break
This will iterate through the list till you get to the right position (takes account of the second spot in case the first one is the same ie [3, 3] and b_list = [3,5]) and append b_list at the index where it stopped
you could use bisect_left to find the insertion index using a binary search (I'm assuming that there are no range overlaps in your data)
a_list = [[1,2], [5,6], [7,8]]
b_list = [3, 4]
from bisect import bisect_left
i = bisect_left(a_list,b_list)
a_list.insert(i,b_list)
print(a_list)
[[1, 2], [3, 4], [5, 6], [7, 8]]
You can also do it by sequentially searching for the index of the first item that is greater than b_list.
a_list = [[1,2], [5,6], [7,8]]
b_list = [3, 4]
i = next((i for i,a in enumerate(a_list) if b_list<a),len(a_list))
a_list.insert(i,b_list)
print(a_list)
[[1, 2], [3, 4], [5, 6], [7, 8]]

How do I take the same index of different lists and put it into seperate lists?

Consider lists
a=[1,2,5,4,3]
b=[2,4,8,3,4]
I want my final lists to be
c=[1,2] d=[2,4] e=[5,8] f=[4,3] g=[3,4]
you can use a for loop:
result = []
for t in zip(a, b):
result.append(list(t))
result
output:
[[1, 2], [2, 4], [5, 8], [4, 3], [3, 4]]
You can use zip.
my_new_lists = list(map(list, zip(a,b)))

Combination of betting odds in Python

So I'm new to Python and I've decided to work on a project that I'm interested in. I've connected to an API to get betting odds from different bookies. I've successfully got the data and stored in a Sqlite3 database. The next step is to compare the odds, and this is where I'm getting stuck.
So let's say I have a list of odds from 3 bookies:
bookie1 = [1,2]
bookie2 = [3,4]
bookie3 = [5,6]
then I have the odds from all bookies in 1 list, such as:
bookies_all = [ [1,2], [3,4], [5,6] ]
How do I get the combinations of odds from the 3 bookies?
I expect the output to look something like this:
combos = [[1,3], [1,5], [1,4], [1,6], [2,3], [2,5], [2,4], [2,6], [3,5], [3,6],[4,5], [4,6]]
Is the best option to loop through the list?
I've coded this up and it gives me all the combinations I need.
bookies_all = [[1, 2], [3, 4], [5, 6]]
combos = []
count = 0
for outer in bookies_all:
for inner in bookies_all:
temp_list = [outer[0], inner[1]]
count += 1
combos.append(temp_list)
print(combos)
Output: [[1, 2], [1, 4], [1, 6], [3, 2], [3, 4], [3, 6], [5, 2], [5, 4], [5, 6]]
The combinations in bold are the ones I want. This code works for this example.
I will test it out for scenarios where the bookies_all list has more values.
You can use itertools.combinations to find the combinations of bookies, then use a list comprehension to interleave the items:
from itertools import combinations
bookies_all = [[1, 2], [3, 4], [5, 6]]
all_comb = list(combinations(bookies_all, 2))
#print(all_comb)
combos = [[i, j] for c in all_comb for i in c[0] for j in c[1]]
print(combos)
Output:
[[1, 3], [1, 4], [2, 3], [2, 4], [1, 5], [1, 6], [2, 5], [2, 6], [3, 5], [3, 6], [4, 5], [4, 6]]

Indices of duplicate lists in a nested list

I am trying to solve a problem that is a part of my genome alignment project. The problem goes as follows:
if given a nested list
y = [[1,2,3],[1,2,3],[3,4,5],[6,5,4],[4,2,5],[4,2,5],[1,2,8],[1,2,3]]
extract indices of unique lists into a nested list again.
For example, the output for the above nested list should be
[[0,1,7],[2],[3],[4,5],[6]].
This is because list [1,2,3] is present in 0,1,7th index positions, [3,4,5] in 2nd index position and so on.
Since I will be dealing with large lists, what could be the most optimal way of achieving this in Python?
You could create an dictionary (or OrderedDict if on older pythons). The keys of the dict will be tuples of the sub-lists and the values will be an array of indexes. After looping through, the dictionary values will hold your answer:
from collections import OrderedDict
y = [[1,2,3],[1,2,3],[3,4,5],[6,5,4],[4,2,5],[4,2,5],[1,2,8],[1,2,3]]
lookup = OrderedDict()
for idx,l in enumerate(y):
lookup.setdefault(tuple(l), []).append(idx)
list(lookup.values())
# [[0, 1, 7], [2], [3], [4, 5], [6]]
You could use list comprehension and range to check for duplicate indexes and append them to result.
result = []
for num in range(len(y)):
occurances = [i for i, x in enumerate(y) if x == y[num]]
if occurances not in result: result.append(occurances)
result
#[[0, 1, 7], [2], [3], [4, 5], [6]]
Consider numpy to solve this:
import numpy as np
y = [
[1, 2, 3],
[1, 2, 3],
[3, 4, 5],
[6, 5, 4],
[4, 2, 5],
[4, 2, 5],
[1, 2, 8],
[1, 2, 3]
]
# Returns unique values of array, indices of that
# array, and the indices that would rebuild the original array
unique, indices, inverse = np.unique(y, axis=0, return_index=True, return_inverse=True)
Here's a print out of each variable:
unique = [
[1 2 3]
[1 2 8]
[3 4 5]
[4 2 5]
[6 5 4]]
indices = [0 6 2 4 3]
inverse = [0 0 2 4 3 3 1 0]
If we look at our variable - inverse, we can see that we do indeed get [0, 1, 7] as the index positions for our first unique element [1,2,3], all we need to do now is group them appropriately.
new_list = []
for i in np.argsort(indices):
new_list.append(np.where(inverse == i)[0].tolist())
Output:
new_list = [[0, 1, 7], [2], [3], [4, 5], [6]]
Finally, refs for the code above:
Numpy - unique, where, argsort
One more solution:
y = [[1, 2, 3], [1, 2, 3], [3, 4, 5], [6, 5, 4], [4, 2, 5], [4, 2, 5], [1, 2, 8], [1, 2, 3]]
occurrences = {}
for i, v in enumerate(y):
v = tuple(v)
if v not in occurrences:
occurrences.update({v: []})
occurrences[v].append(i)
print(occurrences.values())

Creating a unique list with the each subsequent item from a series of lists

How can i create a new list combing the first values of my old lists and then the second ones etc..
list_1 = [1,2,3,4]
list_2 = [1,2,3,4]
list_3 = [1,2,3,4]
new_list = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]]
Pure python:
You can use zip:
new_list = list(map(list, zip(list_1,list_2,list_3)))
>>> new_list
[[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]
Alternative:
numpy:
import numpy as np
new_list = np.array([list_1,list_2,list_3]).T.tolist()
>>> new_list
[[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]
Here's another way to do it using list comprehensions.
new_list = [list(args) for args in zip(list_1, list_2, list_3)]
If we enumerate one list the index from that list to all 3
new_list = [[list_1[i], list_2[i], list_3[i]] for i, _ in enumerate(list_1)]
# [[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]

Categories