Join lists as a result of append in Loop - python-3.x

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, [])

Related

How to get a dict from a list of dict according to some threshold

I have a list of dicts like the one below:
list_dict = [{'Name': 'Andres', 'score': 0.17669814825057983},
{'Name': 'Paul', 'score': 0.14028045535087585},
{'Name': 'Feder', 'score': 0.1379694938659668},
{'Name': 'James', 'score': 0.1348174512386322}]
I want to output another list of dict but only when sum of score is higher than a threshold=0.15
Expected output: [{'name':'Andres', 'score' : 0.1766..}]
I did this, but the code is terrible and the outuput is wrongly formatted
l = []
for i in range(len(list_dict)):
for k in list_dict[i]['name']:
if list_dict[i]['score']>0.15:
print(k)
Maybe this is what you're looking?
Actually you're very close... but just miss a few syntax.
Each item in list_dict is a dictionary, so you can access and ask the score, it should not use index to get the interesting part.
new_dc = list()
for item in list_dict: # each item is a dictionary
if item['score'] > 0.15: # it's better to use a meaningful variable.
new_dc.append(item)
print(new_dc) # [{'Name': 'Andres', 'score': 0.17669814825057983}]
Alternatively you can use List Comprehension:
output = [item for item in list_dict if item['score'] > 0.15]
assert new_dc == output # Silence mean they're the same
1st approach using loop
final_list = []
for each in list_dict: #simply iterate through each dict in list and compare score
if each['score']>0.15:
final_list.append(each)
print(final_list)
2nd approach using list comprehension
final_list = [item for item in list_dict if item['score']>0.15]
print(final_list)

Python: Convert 2d list to dictionary with indexes as values

I have a 2d list with arbitrary strings like this:
lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]
I want to create a dictionary out of this:
{'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}
How do I do this? This answer answers for 1D list for non-repeated values, but, I have a 2d list and values can repeat. Is there a generic way of doing this?
Maybe you could use two for-loops:
lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]
d = {}
overall_idx = 0
for sub_lst in lst:
for word in sub_lst:
if word not in d:
d[word] = overall_idx
# Increment overall_idx below if you want to only increment if word is not previously seen
# overall_idx += 1
overall_idx += 1
print(d)
Output:
{'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}
You could first convert the list of lists to a list using a 'double' list comprehension.
Next, get rid of all the duplicates using a dictionary comprehension, we could use set for that but would lose the order.
Finally use another dictionary comprehension to get the desired result.
lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]
# flatten list of lists to a list
flat_list = [item for sublist in lst for item in sublist]
# remove duplicates
ordered_set = {x:0 for x in flat_list}.keys()
# create required output
the_dictionary = {v:i for i, v in enumerate(ordered_set)}
print(the_dictionary)
""" OUTPUT
{'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}
"""
also, with collections and itertools:
import itertools
from collections import OrderedDict
lstdict={}
lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]
lstkeys = list(OrderedDict(zip(itertools.chain(*lst), itertools.repeat(None))))
lstdict = {lstkeys[i]: i for i in range(0, len(lstkeys))}
lstdict
output:
{'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}

Effective ways to group things into list

I am doing a K-means project and I have to do it by hand, which is why I am trying to figure out what is the best ways to group things according to their last values into a list or a dictionary. Here is what I am talking about
list_of_tuples = [(honey,1),(bee,2),(tree,5),(flower,2),(computer,5),(key,1)]
Now my ultimate goal is to be able to sort out the list and have 3 different lists each with its respected element
"""This is the goal"""
list_1 = [honey,key]
list_2 = [bee,flower]
list_3 = [tree, computer]
I can use a lot of if statements and a for loop, but is there a more efficient way to do it?
If you're not opposed to using something like pandas, you could do something along these lines:
import pandas as pd
list_1, list_2, list_3 = pd.DataFrame(list_of_tuples).groupby(1)[0].apply(list).values
Result:
In [19]: list_1
Out[19]: ['honey', 'key']
In [20]: list_2
Out[20]: ['bee', 'flower']
In [21]: list_3
Out[21]: ['tree', 'computer']
Explanation:
pd.DataFrame(list_of_tuples).groupby(1) groups your list of tuples by the value at index 1, then you extract the values as lists of index 0 with [0].apply(list).values. This gives you an array of lists as below:
array([list(['honey', 'key']), list(['bee', 'flower']),
list(['tree', 'computer'])], dtype=object)
Something to the effect can be achieved with a dictionary and a for loop, using the second element of the tuple as a key value.
list_of_tuples = [("honey",1),("bee",2),("tree",5),("flower",2),("computer",5),("key",1)]
dict_list = {}
for t in list_of_tuples:
# create key and a single element list if key doesn't exist yet
# append to existing list otherwise
if t[1] not in dict_list.keys():
dict_list[t[1]] = [t[0]]
else:
dict_list[t[1]].append( t[0] )
list_1, list_2, list_3 = dict_list.values()

How do you create a new dictionary from a list, using positions to dictate keys and values?

I am trying to determine the most used active users in certain packages. I have a list with the packages and users as the elements. I would like to turn these into dictionary with the package name as the key and the username as the value. The pattern of the list is :
list = ['package1', 'userA', 'userB', 'package2', 'userC',
'userD', 'package3', 'userE', 'userF', ...]
I would like:
dict = {'package1': ['userA', 'userB'],
'package2': ['userC', 'userD'],
'package3': ['userE', 'userF'],
...}
I would like to be able to match the package by name and not by position. I currently have something like:
dict={}
for x in list:
if "package" in x:
dict.fromkeys(list, x)
Thanks for your help.
This is one approach using a simple iteration.
Ex:
lst = ['package1', 'userA', 'userB', 'package2', 'userC', 'userD', 'package3', 'userE', 'userF']
result = []
for i in lst:
if i.startswith("package"):
result.append([i])
else:
result[-1].append(i)
result = {i: v for i, *v in result}
print(result)
Output:
{'package1': ['userA', 'userB'],
'package2': ['userC', 'userD'],
'package3': ['userE', 'userF']}
Check out this code;
In [1]: raw_data = ['package1', 'userA', 'userB', 'package2', 'userC', 'userD',
...: 'package3', 'userE', 'userF']
In [2]: data = {}
In [3]: for el in raw_data:
...: if el.startswith('package'):
...: lastkey = el
...: data[el] = []
...: else:
...: data[lastkey].append(el)
...:
In [4]: data
Out[4]:
{'package1': ['userA', 'userB'],
'package2': ['userC', 'userD'],
'package3': ['userE', 'userF']}
If you can rely upon there always being exactly two users, then you ca easily use a dictionary comprehension with indexing and slicing to produce the keys and value-lists that you need:
output = {lst[i]: lst[i+1:i+3] for i in range(0, len(lst), 3)}
If the number of users might be variable though, you'll need a full loop. You need to remember the most recent package you've seen, and put each subsequent user into its associated list:
output = {}
current_package = unpackaged_users = []
for item in lst:
if item.startswith('package'):
current_package = []
output[item] = current_package
else: # or elif item.startswith('user')?
current_package.append(item)
The unpackaged_users variable will contain a list of any users that were included in the input before the first package was seen. If that can't happen in your code, you could probably do away with that variable (and if you don't initialize current_package before the loop, you'll get an exception if that situation ever comes up).

Dividing the list in Python and print the combinations

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!!

Resources