logo
down
shadow

Reorganise list in list python


Reorganise list in list python

By : Vadim Kadnikov
Date : November 21 2020, 07:31 AM
it fixes the issue I need to reorganise two lists in lists and find the total of each key value sum. , You can use itertools.groupby and itertools.chain :
code :
>>> from itertools import chain , groupby
>>> s=[zip(*i) for i in zip(list1,list2)]
>>> [(set(i).pop(),sum(j)) for i,j in [zip(*i) for i in [list(g) for _,g in groupby(sorted(chain(*s)),lambda x : x[0])]]]
[('a', 13), ('b', 6), ('c', 2), ('d', 1)]
>>> from collections import defaultdict
>>> from itertools import chain
>>> d=defaultdict(list)
>>> for k,v in zip(chain(*list1),chain(*list2)):
...     d[k].append(v)
... 
>>> [(k,sum(v)) for k,v in d.items()]
[('a', 13), ('c', 2), ('b', 6), ('d', 1)]
>>> zip(list1,list2)

[(['a', 'b', 'c'], [3, 5, 2]), (['a', 'b', 'c'], [-5, -2, -3]), (['a', 'b', 'c'], [12, 11, 8]), (['a', 'b', 'c'], [-8, -7, -5]), (['b', 'c'], [2, 3]), (['b', 'c'], [-3, -2]), (['a', 'c'], [23, 21]), (['a', 'c'], [-12, -22]), (['b'], [11]), (['b'], [-11]), (['d'], [22]), (['d'], [-21])]
[[('a', 3), ('b', 5), ('c', 2)], [('a', -5), ('b', -2), ('c', -3)], [('a', 12), ('b', 11), ('c', 8)], [('a', -8), ('b', -7), ('c', -5)], [('b', 2), ('c', 3)], [('b', -3), ('c', -2)], [('a', 23), ('c', 21)], [('a', -12), ('c', -22)], [('b', 11)], [('b', -11)], [('d', 22)], [('d', -21)]]
>>> t=sorted(chain(*s))
>>> t
[('a', -12), ('a', -8), ('a', -5), ('a', 3), ('a', 12), ('a', 23), ('b', -11), ('b', -7), ('b', -3), ('b', -2), ('b', 2), ('b', 5), ('b', 11), ('b', 11), ('c', -22), ('c', -5), ('c', -3), ('c', -2), ('c', 2), ('c', 3), ('c', 8), ('c', 21), ('d', -21), ('d', 22)]
>>> [list(g) for _,g in groupby(t,lambda x : x[0])]
[[('a', -12), ('a', -8), ('a', -5), ('a', 3), ('a', 12), ('a', 23)], [('b', -11), ('b', -7), ('b', -3), ('b', -2), ('b', 2), ('b', 5), ('b', 11), ('b', 11)], [('c', -22), ('c', -5), ('c', -3), ('c', -2), ('c', 2), ('c', 3), ('c', 8), ('c', 21)], [('d', -21), ('d', 22)]]
>>> a=[zip(*i) for i in [list(g) for _,g in groupby(t,lambda x : x[0])]]
[[('a', 'a', 'a', 'a', 'a', 'a'), (-12, -8, -5, 3, 12, 23)], [('b', 'b', 'b', 'b', 'b', 'b', 'b', 'b'), (-11, -7, -3, -2, 2, 5, 11, 11)], [('c', 'c', 'c', 'c', 'c', 'c', 'c', 'c'), (-22, -5, -3, -2, 2, 3, 8, 21)], [('d', 'd'), (-21, 22)]]
>>> [(set(i),sum(j)) for i,j in a]
[(set(['a']), 13), (set(['b']), 6), (set(['c']), 2), (set(['d']), 1)]


Share : facebook icon twitter icon
python: Searching strings in one list in another list, then appending an entire list entry to a new list

python: Searching strings in one list in another list, then appending an entire list entry to a new list


By : user2661265
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Example: , Try
code :
s = set(L1)
new_list = [a for a in L2 if any(b in s for b in a)]
Check if items in list a are found in list b and return list c with matching indexes of list b in Python

Check if items in list a are found in list b and return list c with matching indexes of list b in Python


By : user3792485
Date : March 29 2020, 07:55 AM
will help you You can use index from your second list, while iterating over elements of the first list in a list comprehension.
code :
>>> a = ["string2" , "string4"]
>>> b = ["string1" , "string2" , "string3" , "string4" , "string5"]
>>> c = [b.index(i) for i in a]
>>> c
[1, 3]
>>> [b.index(i) for i in a if i in b]
[1, 3]
Split python list in filtered list of multiple list and store them in single list

Split python list in filtered list of multiple list and store them in single list


By : Harshad Holkar
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Sorting can be expensive for large lists.
Starting with your data:
code :
my_list = [
   {'name': 'Sasha', 'category': 'Dog'}, 
   {'name': 'Meow', 'category': 'Cat'}, 
   {'name': 'Bark', 'category': 'Dog'}
]
res = []
seen = {}
for entry in my_list:
    val = seen.setdefault(entry['category'], [])
    if not val:
        res.append(val)
    val.append(entry)
import pprint

pprint.pprint(res)

[[{'category': 'Dog', 'name': 'Sasha'}, {'category': 'Dog', 'name': 'Bark'}],
 [{'category': 'Cat', 'name': 'Meow'}]]
R: Reorganise 2D list of dataframes into one dataframe

R: Reorganise 2D list of dataframes into one dataframe


By : taka
Date : March 29 2020, 07:55 AM
it should still fix some issue This is possibly a simple question, but most of my R experience is with dataframes and dplyr. I have list of lists, where the inner list contains one 'information' dataframe and one 'results' dataframe (see example below). , Since you are familiar with dplyr, try this:
code :
bind_rows(lapply(data,function(i)do.call(cbind,i)))
python list comprehension: making list of multiple items from each list within a list of lists

python list comprehension: making list of multiple items from each list within a list of lists


By : user2385812
Date : March 29 2020, 07:55 AM
hop of those help? I have a list of lists, each with four items. For each list within it, I want to take indexes 0 and 2, put them in a list, then put all those lists in one list of lists. So, using for loops, I got what I wanted by doing this: , Why not:
code :
weekendtemps = [[x[0],x[2]] for x in weather_data if (x[1] == "Saturday" or x[1] == "Sunday")]
weekendtemps = [[x[0],x[2]] for x in weather_data if x[1] in ['Saturday', 'Sunday']]
Related Posts Related Posts :
  • Remove commas in a string, surrounded by a comma and double quotes / Python
  • How to chain Django querysets preserving individual order
  • Comparison with Python
  • How to find backlinks in a website with python
  • Return new instance of subclass when using methods inherited from parent class in Python
  • Which function in django.contrib.auth creates the default model permissions?
  • Formatting text in tabular form with Python
  • How to determine the first day of a month in Python
  • Error while converting date to timestamp in python
  • Python string iterations
  • Is there any file number limitation when you select multiple files with wxFileDialog?
  • Errors with Matplotlib when making an executable with Py2exe (Python)
  • Django Haystack - Indexing single field
  • Go Pro Hero 3 - Streaming video over wifi
  • Appending a column in .csv with Python/Pandas
  • How to change my result directory in Robot framework using RIDE?
  • problem with using pandas to manipulate a big text file in python
  • python-magic module' object has no attribute 'open'
  • Where goes wrong for this High Pass Filter in Python?
  • Why inserting keys in order into a python dict is faster than doint it unordered
  • flann index saving in python
  • Create new instance of list or dictionary without class
  • How can I easily convert FORTRAN code to Python code (real code, not wrappers)
  • Address of lambda function in python
  • Python adding space between characters in string. Most efficient way
  • python http server, multiple simultaneous requests
  • Disguising username & password on distributed python scripts
  • Post GraphQL mutation with Python Requests
  • Why doesnt pandas create an excel file?
  • Rolling comparison between a value and a past window, with percentile/quantile
  • How to avoid repetitive code when defining a new type in python with signature verification
  • How to configure uWSGI in order to debug with pdb (--honour-stdin configuration issue)
  • In Python, how do you execute objects that are functions from a list?
  • Python- Variable Won't Subtract?
  • Processing Power In Python
  • Python 2.7.2 - Cannot import name _random or random from sys
  • Why doesn't the Python sorted function take keyword order instead of reverse?
  • Make a function redirect to other functions depending on a variable
  • get_absolute_url in django-categories
  • Monitoring non-Celery background task with New Relic in Python
  • Feature selection with LinearSVC
  • LSTM - Predicting the same constant values after a while
  • Test the length of elements in a list
  • Django: render radiobutton with 3 columns, cost column must change according to size & quantity selected
  • Python class attributes vs global variable
  • sys.stdout.writelines("hello") and sys.stdout.write("hello")
  • is ndarray faster than recarray access?
  • Python - search through directory trees, rename certain files
  • GAE: How to build a query where a string begins with a value
  • TypeError: __init__() takes at least 2 arguments (1 given)
  • Overriding and customizing "django.contrib.auth.views.login"
  • Django : Redirect to a particular page after login
  • Python search and copy files in directory
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org