logo
down
shadow

How to get the average of many lists embedded within each other?


How to get the average of many lists embedded within each other?

By : lexstephen
Date : October 24 2020, 06:10 AM
it should still fix some issue A simple implementation that supports nested lists, does without any specific library and works with any python version:
code :
def nested_avg(elements):
    try:
        seq = iter(elements)
    except TypeError:
        return elements
    s = 0
    while True:
        try:
            el = next(seq)
        except StopIteration:
            return s / len(elements)
        s += nested_avg(el)


l1=[2,3,[4,6]]
print(int(nested_avg(l1)))

l2=[2,3,[4,[5,7]]]
print(int(nested_avg(l2)))


Share : facebook icon twitter icon
Advice with lists, for loops, and user lists iput in order to create a calculator that calculates average

Advice with lists, for loops, and user lists iput in order to create a calculator that calculates average


By : Desarrollo Nevada
Date : March 29 2020, 07:55 AM
hop of those help? what you are doing wrong is changing knowledge from a list [100,90] into an int 190
for n in 190 is not a valid statement
how to turn a string of letters embedded in squared brackets into embedded lists

how to turn a string of letters embedded in squared brackets into embedded lists


By : Heroicguy
Date : March 29 2020, 07:55 AM
will be helpful for those in need I'm trying to find a simple way to convert a string like this:
code :
>>> import json
>>> a = '[[a b] [c d]]'
>>> a = ''.join(map(lambda x: '"{}"'.format(x) if x.isalpha() else x, a))
>>> a
'[["a" "b"] ["c" "d"]]'
>>> json.loads(a.replace(' ', ','))
[[u'a', u'b'], [u'c', u'd']]
>>> a = '[[[a b] [c d]] [[e f] [g h]]]'
>>> ...
>>> json.loads(a.replace(' ', ','))
[[[u'a', u'b'], [u'c', u'd']], [[u'e', u'f'], [u'g', u'h']]]
>>> import json
>>> a = '[[X v] -s]'
>>> a = ''.join(map(lambda x: '"{}"'.format(x) if x.isalpha() or x=='-' else x, a))
>>> json.loads(a.replace('[ [', '[[').replace('] ]', ']]').replace(' ', ',').replace('][', '],[').replace('""',''))
[[u'X', u'v'], u'-s']
Reorder a Python list of lists according to the second element of embedded lists

Reorder a Python list of lists according to the second element of embedded lists


By : juleshoward
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Using the built-in function sorted:
code :
>>> l = [[1, 'A'], [2, 'B'], [3, 'B'], [4, 'A'], [5, 'C']]
>>> from operator import itemgetter
>>> sorted(l, key=itemgetter(1))
[[1, 'A'], [4, 'A'], [2, 'B'], [3, 'B'], [5, 'C']]
Trouble Appending to Lists Embedded in Lists

Trouble Appending to Lists Embedded in Lists


By : Albert So
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Python dictionary will do a better mapping between strings and values.
code :
myd = {"A": 1, "B": 2, "C": 0}
myd["C"] = 3
myd.update({"D": 4}) # this will add D
X = ["A", "B", "C"]
Y = [1]
Z = [X, Y]
for i in X:
    val = X.index(i) + 1
    if val not in Y:
        Y.append(val)
Average across lists of lists in numpy

Average across lists of lists in numpy


By : user3085151
Date : March 29 2020, 07:55 AM
wish helps you Create np.array from list of lists li specifying dtype='object' and swapaxes to group same s into same group. Slicing 2 last elements on axis 2 (right-most axis), and sum, and divide it by num_exp. Finally, column_stack unique string values to it.
code :
num_exp = 3
li = [[["s1", 1, 2], ["s2", 3, 4], ["s3", 5, 6]],
      [["s1", 2, 3], ["s2", 4, 5], ["s3", 6, 7]],
      [["s1", 3, 4], ["s2", 5, 6], ["s3", 7, 8]]]

arr = np.array(li, dtype='object').swapaxes(0, 1)

Out[372]:
array([[['s1', 1, 2],
        ['s1', 2, 3],
        ['s1', 3, 4]],

       [['s2', 3, 4],
        ['s2', 4, 5],
        ['s2', 5, 6]],

       [['s3', 5, 6],
        ['s3', 6, 7],
        ['s3', 7, 8]]], dtype=object)

arr1 = arr[...,[1,2]].sum(axis=1) / num_exp

Out[380]:
array([[2.0, 3.0],
       [4.0, 5.0],
       [6.0, 7.0]], dtype=object)

s = arr[:,0, 0]
result = np.column_stack([s, arr1])

Out[389]:
array([['s1', 2.0, 3.0],
       ['s2', 4.0, 5.0],
       ['s3', 6.0, 7.0]], dtype=object)
Related Posts Related Posts :
  • Percent signs in windows path
  • How to add a random number to a subsection of a numpy array?
  • How to generate all the values of an iterable besides the last few?
  • Searching by both class and range in XPath
  • Python code execution in Perl interpreter
  • Best Way to Include Variable in Python3
  • Serialize the @property methods in a Python class
  • What is the most platform- and Python-version-independent way to make a fast loop for use in Python?
  • Good way to edit the previous defined class in ipython
  • Bounced email on Google App Engine
  • Search jpeg files using python
  • Dynamically create class attributes
  • python unichr problem
  • Python beginner, strange output problem
  • Python: Finding a value in 1 list and finding that corresponding index in another list
  • can't install mysqlclient on mac os x mojave
  • Error indicates flattened dimensions when loading pre-trained network
  • how to replace underlines with words?
  • Adding through iteration
  • Use OpenCV on deployed Flask app (Heroku)
  • How to skip interstitial in a django view if a user hits the back button?
  • Any Naive Bayesian Classifier in python?
  • Python 2.5.2: remove what found between two lines that contain two concrete strings
  • Python 2.5.2 script that add "The function starts here" to all the functions of the files of a directory
  • HttpResponseRedirect question
  • Python socket error on UDP data receive. (10054)
  • Encoding issues with cloud ml
  • numpy.where - Weird behaviour: new elements spawning from nowhere?
  • I can't move my player in pygame, can you figure why?
  • Weird error I receive from Tkinter in Python
  • Using a Zapier Custom Request Webhook with JSON Web Tokens
  • Keras: Use categorical_crossentropy without one-hot encoded array of targets
  • Does python's httplib.HTTPConnection block?
  • Do alternate python implementation version numbers imply that they provide the same syntax?
  • Searching for specific HTML string using Python
  • python sax error "junk after document element"
  • MySql: How to know if an entry is compressed or not
  • Return a list of imported Python modules used in a script?
  • Returning a list in this recursive coi function in python
  • Python2.6 Decimal to Octal
  • Appengine Apps Vs Google bot web crawler
  • Changing models in django results in broken database?
  • Global variable functions
  • Using lambda inside a function
  • How to open a file, replace some strings, and save updates to the same file?
  • How to move the beginning of an input to the and?
  • If else fill variable if empty list
  • Pandas: Find and print all floats in column
  • sqlite3.OperationalError: database is locked - non-threaded application
  • How to implement mib module in net-snmp with python?
  • Does Python/Scipy have a firls( ) replacement (i.e. a weighted, least squares, FIR filter design)?
  • sorl-thumbnail and file renaming
  • Python -- what is NOT in 2.7 that IS in 3.1? So many things have been back-ported, what is NOT?
  • How to make a Django model fields calculated at runtime?
  • Django - Threading in views without hanging the server
  • Python: Why is my POST requests not working?
  • Tried to add a value to a while condition, but it doesn't go back
  • How do I exit a while-true loop after 5 tries?
  • win python3 Multithreading
  • Compare 2 dictionaries in python
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk