logo
down
shadow

I'm trying to compute the sum of an alphanumeric list


I'm trying to compute the sum of an alphanumeric list

Content Index :

I'm trying to compute the sum of an alphanumeric list
Tag : python , By : RyanMcG
Date : November 29 2020, 04:01 AM

fixed the issue. Will look into that further If you really want to summ up flight-numbers, you can create tuples from your raw data directly and summ them into a dict: (using a defaultdict would be better)
t = ['AI077:077', 'AI077:077', 'AI077:077', 'AI077:077', 'AI567:567',
     'AI567:567', 'BA896:896', 'SI267:267', 'SI267:267', 'SI267:267']

trimmed = [(y[0:5],int(y[6:])) for y in t]

summs = {}
for flight,price in trimmed:
    summs.setdefault(flight,0)
    summs[flight] += price

print(summs) 
{'BA896': 896, 'SI267': 801, 'AI077': 308, 'AI567': 1134}
               #flight : from : to : seat-number
ticket_list= ["AI567:MUM:LON:014", "AI077:MUM:LON:056", "BA896:MUM:LON:067",
              "SI267:MUM:SIN:145", "AI077:MUM:CAN:060", "SI267:BLR:MUM:148", 
              "AI567:CHE:SIN:015", "AI077:MUM:SIN:050", "AI077:MUM:LON:051",
              "SI267:MUM:SIN:146"]

from collections import Counter
c = Counter ((t.split(":")[0] for t in ticket_list))

print(c)
# sold tickets per flight
Counter({'AI077': 4, 'SI267': 3, 'AI567': 2, 'BA896': 1})
from itertools import groupby

# if you need the tickets as well:
grp = groupby(sorted(ticket_list), lambda x:x[:6])

for g in grp:
    key, seats = g
    seats = list(seats)
    print(f"Flight: {key} has sold seats {len(seats)}: {','.join( x.split(':')[-1] for x in seats)}")

Flight: AI077: has sold seats 4: 060,051,056,050
Flight: AI567: has sold seats 2: 015,014
Flight: BA896: has sold seats 1: 067
Flight: SI267: has sold seats 3: 148,145,146

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Natural sort of a list of lists based on an alphanumeric string within sub-list?


Tag : python , By : KL.
Date : March 29 2020, 07:55 AM
hope this fix your issue Using the natural_sort function from this answer you can do something like this:
import re
from string import punctuation as punc, whitespace as wt
from pprint import pprint

def natural_sort(l): 
    #https://stackoverflow.com/a/4836734/846892
    convert = lambda text: int(text) if text.isdigit() else text.lower() 
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
    return sorted(l, key = alphanum_key)

def key(seq):                                           
    convert = lambda text: int(text) if text.isdigit() else text.lower() 
    return [convert(c.translate(None, punc+wt)) for c in re.split('([0-9]+)', seq)]
... 
>>> my_list = [[ 1,   'C1', 'DW-00232'],
 [3,    'C11, C32, C46', 'DW-6546'],
 [7,    'C16, C17, C18, C19, C20, C21, C25', 'DW-545'],
 [5,    'C2, C3, C4, C5, C63', 'DW-7657'],
 [1,    'C26', 'DW-0056'],
 [2,    'C59, C60', 'DW-23424'],
 [5,    'C6, C13, C24, C30, C64', 'DW-5345']]
>>> 
>>> new_lis = [x[:1] + [", ".join(natural_sort(x[1].split(', ')))] + x[2:]
                                                                for x in my_list]
>>> new_lis.sort(key = lambda x:key(x[1]))               
>>> pprint(new_lis)
[[1, 'C1', 'DW-00232'],
 [5, 'C2, C3, C4, C5, C63', 'DW-7657'],
 [5, 'C6, C13, C24, C30, C64', 'DW-5345'],
 [3, 'C11, C32, C46', 'DW-6546'],
 [7, 'C16, C17, C18, C19, C20, C21, C25', 'DW-545'],
 [1, 'C26', 'DW-0056'],
 [2, 'C59, C60', 'DW-23424']]
>>> 

How to compare an alphanumeric string with a List<string> which also has alphanumeric values C#


Tag : chash , By : Karina
Date : March 29 2020, 07:55 AM
may help you . Why you want use Linq for this simple task? You can simply use List.Contains(item) method
        List<string> lollipop = new List<string>();
        //Do something
        if(lollipop.Contains("lollipop"))
         //DO something
        else
        //Something else

What would be the regex for this pattern; (alphanumeric.alphanumeric.alphanumeric)?


Tag : regex , By : Longchao Dong
Date : March 29 2020, 07:55 AM
wish helps you I am new to regex. What would be the regex for this pattern? , How about:
/\((\w+\.\w+\.\w+)\)/

Get the index of a non-alphanumeric-string in a list containing non-alphanumeric elements in python


Tag : python , By : Thomas Plunkett
Date : March 29 2020, 07:55 AM
Hope that helps I think you are looking in the wrong list. Instead of looking in the index, try looking in content
with open('test.txt', "r") as file:
    for line in file:
        print find_element_in_list(content, line.rstrip('\n'))

A service account has "Compute Admin" permission but an error says that compute.instances.list is needed


Tag : google-cloud-platfor , By : fstender
Date : October 03 2020, 11:00 AM
it fixes the issue There are two service accounts used by GCF:
Cloud Functions service account Runtime service account
Related Posts Related QUESTIONS :
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • I have a regex statement to pull all numbers out of a text file, but it only finds 77 out of the 81 numbers in the file
  • How do I create a dataframe of jobs and companies that includes hyperlinks?
  • Detect if user has clicked the 'maximized' button
  • Does flask_login automatically set the "next" argument?
  • Indents in python 3
  • How to create a pool of threads
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • How do I get LOAD_CLASSDEREF instruction after dis.dis?
  • Django - How to add items to Bootstrap dropdown?
  • Linear Regression - Does the below implementation of ridge regression finding coefficient term using gradient method is
  • How to drop all rows in pandas dataframe with negative values?
  • Most Efficient Way to Find Closest Date Between 2 Dataframes
  • Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments
  • Looping through a function
  • Create a plot for each unique ID
  • a thread python with 'while' got another thread never start
  • Solution from SciPy solve_ivp contains oscillations for a system of first-order ODEs
  • trigger python events driven by selenium controlled browser
  • Passing line-edits to a contextmanager to set validators
  • Python: globals().items() iterations try to change a dict
  • Is it possible to specify starting values for each parameter (instead of bounds) for scipy's differential evolution?
  • why datetime.now() and constructed datetime using all fields(like year,month...) of now has big timedelta?
  • MySQL multiple table UPDATE query using sqlalchemy core?
  • find if a semantic version is superset of of another version python
  • Type checking against dynamically created objects
  • Struggling with simple reverse function
  • Is there a function for finding the midpoint of n points on sklearn.neighbors.NearestNeighbors?
  • How to set max number of tweets to fetch
  • PYTHON 3.7.4 NOT USING SQLITE 3.29.0
  • How to replace Nan value with zeros in a numpy array?
  • How to speed up calculating variance among sparse matrix
  • cupy code is not fast enough compared with numpy
  • How to count frequency of select values in Python pandas dataframe
  • Scrape Span Text from Google
  • Python watchdog, watch a directory and rename file on event.modification
  • Filtering rows in DataFrame with dependent conditions
  • How to check if a character is a not a part of number or URL in string?
  • Compare corresponding elements of a list
  • Python misinterprets 3 character string as UTF-8 continuation byte
  • Merge two columns in Pandas
  • Side Effect error in Python in an online compiler
  • How to convert a navigation list with depth levels to a parent-child flat list?
  • Retrieving values from a paired key dictionary in Python
  • How to test the current text of a Tkinter text box widget before inserting new text after user clicks on a button?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com