python PYTHON_LISTS

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python PYTHON_LISTS相关的知识,希望对你有一定的参考价值。

#! python3
# tablePrinter.py - A function to pretty print a nested list
# Author: Priyank Jain
tableData = [['apples', 'oranges', 'cherries', 'banana'],
	['Alice', 'Bob', 'Carol', 'David'],
	['dogs', 'cats', 'moose', 'goose']]
    
    
tableData2 = [ ['1', '2', '3', '4'], [ '3', '4', '5', '6' ], [ '1', '2', '3', '5'] ] 

def printTable(nestedList):
	maxColumnLength = []
	for innerList in nestedList:
		maxColumnLength.append(max(map(len, innerList)))
	if nestedList and len(nestedList) > 0:
		for rowNum in range(len(nestedList[0])):
			for colNum in range(len(nestedList)):
				print(nestedList[colNum][rowNum].rjust(maxColumnLength[colNum]),end = ' ')
			print()

printTable(tableData)
printTable(tableData2)




def print2Dtable(input_list):
    r"""
    Function: print2Dtable(input_list)
    Name:   print2Dtable
    Input:  list (nested)
    Output: nothing, prints a preformatted 2d table
    Usage:  printTable(tableData)
    Notes:  nested list needs to contain lists of similar size. 
    Location: PYTHON LISTS
    """
    
    # Initiate max
    maxColumnLength = []
    
    # Iterate over lists in the nested list
	for innerList in nestedList:
		maxColumnLength.append(max(map(len, innerList)))
        
    # Compare
	if nestedList and len(nestedList) > 0:
		
        # Iterate over elements
        for rowNum in range(len(nestedList[0])):
			for colNum in range(len(nestedList)):
				print(nestedList[colNum][rowNum].rjust(maxColumnLength[colNum]),end = ' ')
			print()

Functions that modify lists:
  1.  flatten_list           = Flattens a nested list
  2.  list2tuple             = Converts a list to tuple
  3.  tuple2list             = Converts a tuple to list
  4.  unflatten_list         = Groupify a list into a nested list
  5.  randomize_list         = randomizes list elements
  6.  sort_odds_evens        = Sorts odds and even elements in a list
  7.  reverse_list           = Reverses the sequence of list elements
  8.  count_elements         = Counts elements of a list, stores in dictionary
  9.  is_empty_list          = Checks if a list is empty
  10. is_numeric_list        = Checks if a list contains only numbers(any)
  11. intersect_list         = Compares two lists and finds the intersection
  12. symmetric_list         = Compares two lists and finds the symmetric difference
  13. find_duplicates_list   = Find and list duplicates only in dictionary
  14. remove_duplicates_list = Find and remove all duplicate values
  15. apply_to_list          = Apply outer function to all elements of a list
  16. sequentialSearch       = Sequential search in a list, returns index
  17. binarySearch           = Binary search in a list, returns index
  18. count_smaller          = Counts elements smaller than limit
  19. filter_smaller         = Filters out elements smaller than a limit
  20. count_bigger           = Counts elements bigger than a limit
  21. filter_bigger          = Filters out elements bigger than a limit
  22. compare_lists          = Compares two lists and calculates differences
  23. custom_filter          = Applies a custom filter to a list
  24. element_frequency      = Counts frequency of element in list, stores in dictionary
  25. pad_list               = Pads a list (Left or right) with specified padding up to target
  26. list_splitter          = Splits a list into smaller sublists of specified size
  27. make_list              = Converts any iterable to list
  28. stringtolist           = Converts a string to list
  29. listtostring           = Converts a string into a list
  30. listtotuple            = Converts a list into a tuple
  31. listtointfloatstr      = Converts a list into integer / float / string
  32. simolatestackLIFO      = Simulate a stack with lists, LIFO
  33. simulatequeueFIFO      = Simulate a queue with lists, FIFO
  38. listtocsv              = Converts list to comma separated string (or delimited)
  39. insertatindex          = Inserts an integer or list at a specific index in list (Embedded or not)
  40. list_removebeg         = Removes elements from the beginning of a list (X elements)
  41. list_removeend         = Removes elements from the end of a list (X elements)
  42. list_removemid         = Removes elements at specified index from middle of list
  43. Print2Dnested.py       = Prints a formatted 2d table out of a nested list.
def list_removemid(lista, numberstart, numberend):
  '''
  Name: list_removemid
  Function: Removes elements between index and index
  Used as: print (list_removemid(b, 1, 4)) 
  Notes: Can work on strings and tuples
  '''
    output_list = lista[:numberstart] + lista[numberend+1:]
    return output_list
    
    
a = 'panagos'
b = [ 1, 2, 3, 4, "x", 5, 3, 2, 7, 6 ]
c = ( 1, 2, 3,)


print (list_removemid(b, 1, 4))
def list_removeend(lista, number):
  '''
  Name: list_removeend
  Function: Removes elements from the end of a list
  Used as: a = list_removeend(lista, 2)
  Notes: Can work on strings and tuples
         Does not edit in place
  '''
    lengthof = len(lista)
    calc = lengthof - number
    output_list = lista[:calc]
    return output_list
    
    
    
a = 'panagos'
b = [ 1, 2, 3, 4, "x", 5, 3, 2, 7, 6 ]
c = ( 1, 2, 3,)

#print (list_removeend(a, 1))
#print (list_removeend(b, 2))
#print (list_removeend(c, 1))
def list_removebeg(lista, number):
  '''
  Name: list_removebeg
  Function: Removes elements from beginning of list
  Used as: a = list_removebeg(lista, 2)
  Notes: Can work on strings and tuples. 
         Does not edit in place.
  '''
    output_list = lista[number:]
    return output_list


a = 'panagos'
b = [ 1, 2, 3, 4, "x", 5, 3, 2, 7, 6 ]
c = ( 1, 2, 3,)

#print (list_removebeg(a, 2))
#print (list_removebeg(b, 3))
#print (list_removebeg(c, 1))
def insert_in_list(lista, new, location, embed = "yes"):
    b = []

    if isinstance(new, (list,)):
        print ('aaaaa')

    if type(new) is list and embed == "yes":
        new = [ new ]
        b = lista[:location] + new + lista[location:]
        return b
    elif (type(new) is list) and embed != "yes":
        b = lista[:location]
        for j in new:
            b.append(j)
        b = b + lista[location:]
        return b
    else:
        print("incorrent")
        return false




a = [ 1, 2 ,3 , 4]
b = [ 5, 1, 3, "b" ] 
print (insert_in_list(a, b, 2, embed = "no"))
def listtocsv(lista, endcomma = "yes"):
    outstring = ''
    for j in lista:
        outstring = outstring + str(j) + ";"
        
    if endcomma == "no":
        outstring = outstring[:-1]
    
    return outstring    
    
    
    
    
def listtocsvany(lista, endcomma = "yes", delim = ";")    
    outstring = ''
    for j in lista:
        outstring = outstring + str(j) + str(delim)
        
    if endcomma == "no":
        outstring = outstring[:-1]
    
    return outstring    
    
a = [1,2,3,4,5,6,7,8,9]

def unflatten_list(lista, grouping):
  '''
  Function : unflatten_list
  Description : Converts a list into a list of lists
  Inputs : List (Simple)
           grouping (How many values grouped together)
  Output : List of Lists (Based on grouping)
  Usage(print): print (unflatten_list(a,3))
  Usage(Assign): b = unflatten_list(a,3))
  '''
    i=0
    new_list=[]
    while i<len(lista):
        new_list.append(lista[i:i+grouping])
        i+=grouping
    return new_list        
        

print (unflatten_list(a, 2))
def tuple2list(tuple):
  '''
  Function : tuple2list
  Description : Converts a tuple into a list
  Inputs : Tuple
  Output : List
  Usage(print): print (tuple2list(tuple))
  Usage(Assign): b = tuple2list(tuple))
  '''
  outlist = []
  for j in tuple:
    outlist.append(j)
  return outlist
  
def symmetric_list(a, b):
  '''
  Function: symmetric_list
  Description: Finds the set intersection between two lists
  Inputs : Two Lists (Any)
  Outputs: One list, the symmetric difference
  Usage(print): print (symmetric_list(c1,c2))
  Usage(assign): b = symmetric_list(c1,c2))
  '''
  result=[]
  for i in b:
    if isinstance(i,list):
      # if element is list, recursive call
      result.append(symmetric_list(a,i))
    else:
      # if element is normal, simple check and append
      if i not in a:
        result.append(i)
  return result
    
# Example    
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

print (symmetric_list(c1,c2))
def sort_odds_evens(lista):
  '''
  Function: sort_odds_evens
  Description: Sorts odds and evens
  Inputs: List of integers
  Outputs: 2 lists, odds and evens
  Usage: sort_odds_evens(list)
  '''
  odds = []
  evens = []
  for number in lista:
    if number%2==0:
      evens.append(number)
    else:
      odds.append(number)
  return (evens, odds)
    
a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

print (sort_odds_evens(a))
def stack(element, list1):
    '''
    Function : stackadd
    Description : Stacks the next element on a stack(FIFO)
    Input: element, list
    Output : List with one stacked element
    Usage: x = queuestack(10, lista)
    Notes: FIFO = FIRST IN, FIRST OUT
           queuestack will add an element to the top of th elist
    '''
    list1.append(element)
    return list1

def destack(list1):
    '''
    Function : stackrem
    Description : Removes the first element from a queue(FIFO)
    Input : list
    Output : list - the first element
    Usage : b = queuedestack(lista1)
    Notes: The first element is the one on the far right, the
    one we add if we use queuestack, queues are FIFO.
    '''
    b = list1.pop()
    return (list1, b)
    
    
a = [ 1,3,5,7]

a = stack(10, a)
print (a)

a = destack(a)
print (a[0])
print (a[1])
def sequentialSearch(alist, item):
  '''
  Function: sequentialSearch
  Description: Sequential search on list
  Input: List
  Output: Tuple of boolean, index
  Usage: SequentialSearch(list, item)
  Notes: Does not edit list in place
  '''
    pos = 0
    found = False
	
    while pos < len(alist) and not found:
        if alist[pos] == item:
            found = True
        else:
            pos = pos+1
	
    return (found, pos)
	
testlist = [1, 2, 32, 8, 17, 19, 42, 13, 0]

print(sequentialSearch(testlist, 3))
print(sequentialSearch(testlist, 13))
def reverse_list(lista):
  '''
  Function: reverse_list
  Description: Reverses the order of a list
  Inputs: List
  Output: Reversed list
  Usage: reverse_list(list)
  Notes: Does not edit in place
  '''
    outlist = []
    for i in lista:
        outlist.insert(0, i)
        
    return outlist
    
a = [ 1,2,3,4,5]

print (reverse_list(a))
a = [ 1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 7 ]


def rem_duplicates_list(x):
  '''
  Function : rem_duplicates_list
  Description : Counts elements, removes duplicates
  Inputs : List (Simple)
  Output : Dictionary of count of elements
           List with removed duplicates
           * (Joined in tuple)
  Usage(print): print (rem_duplicates_list(x))
  Usage(Assign): b = rem_duplicates_list(x)
  '''
    seen = dict()
    outlist = []
    for j in x:
        if j not in seen:
            seen[j] = 1
            outlist.append(j)
        else:
            seen[j] += 1
    return (outlist, seen)
    
print (rem_duplicates_list(a)[0])
print (rem_duplicates_list(a)[1])
print (rem_duplicates_list(a))

##########################################################
# SECOND WAY

def randomize_list(list):
    '''
    Function : randomize_list
    Description : Shuffles element of list
    Inputs : List (Simple)
    Output : Shuffled List
    Usage(print): print (randomize_list(a))
    Usage(Assign): b = randomize_list(a)
    '''
    #import modules
    import random
    
    inlist = list
    outlist = []
    x = 0
    
    for i in (range(len(list)):
        # calculate random index
        x = random.randint(0,len(inlist)-1)
        #Append new element to outlist
        outlist.append(list[x])
        # remove element from inlist
        del inlist[x]
    return outlist
def padlist(lst,target,padding, position = 1):
  '''
  Function : padlist
  Description : Pads a list with specified padding up to target
  Inputs : list, target (ie 30), padding (ie '0'), 1 or 0
  Output : List with padding
  Usage : a = padlist(list, 30, 'a', 1)
  Notes : Does not edit list in place
  Notes2: Position(1) = Left / Position(2) = Right
  '''
    outlist = []
    templist = []
    length = len(lst)
    if target < length:
        return False
    elif target == length:
        return lst
    else:
        # Calc dif
        diffdigit = target - length
        while diffdigit > 0:
            templist.append(padding)
            diffdigit -= 1
            
        if position == 1: 
            outlist = templist + lst
            return outlist
        else:
            outlist = lst + templist
            return outlist
        
a = [ 1, 2, 3, 4 ]
print (padlist(a, 15, '0', 1))
def makelist(data):
  '''
  Function: makelist
  Description: Converts any data type to list
  Input: any iterable data type
  Output: List
  Usage: a = makelist(dict/tuple etc)
  Notes: When used in dicts, it stores only keys in list
  '''
  
    if isinstance(data, (tuple, list, set, dict)):
        return list(data)
    elif data:
        return [data]
    else:
        return []




a = ( 1, 2, 3, 4, 5 )
b = { 1:2, 2:3, 4:3 }

print (makelist(a))
print (makelist(b))
def listtotuple(list):
    out = ()
    for j in list:
        out += (j,)
    return out
def listtostr(list):
    out = ''
    for s in list:
        out += str(s)
    return out
# source: webpy
def group(seq, size):
    """
    Function: group
    Description: Splits a list into sublists based on group size
    Input: List, group-size
    Output: List of smaller Lists
    Notes: Edits list in place
    Usage: Returns an iterator over a series of lists of length size from iterable.
        >>> list(group([1,2,3,4], 2))
        [[1, 2], [3, 4]]
        >>> list(group([1,2,3,4,5], 2))
        [[1, 2], [3, 4], [5]]
    """

    def take(seq, n):
        for i in xrange(n):
            yield seq.next()

    if not hasattr(seq, 'next'):
        seq = iter(seq)
    while True:
        x = list(take(seq, size))
        if x:
            yield x
        else:
            break




print list(group([1, 2, 3, 4, 5, 6, 7, 8, 9], 2))


#####


def splitbynlist(lista, n):
    outlist = []
    while lista:
        outlist.append(lista[:n])
        lista = lista[n:]
    return outlist

print (splitbynlist([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 2))
def listfreq(lista):
  '''
  Function: listfreq
  Description : Calculates frequencies of elements in list
  Inputs : list
  Output : dictionary of frequencies
  Usage : print (listfreq(a))
  Notes : Stores them in dictionary
  '''
    fq = {}
    
    for w in lista:
        if w in fq:
            fq[w] += 1
        else:
            fq[w] = 1
        
    return fq
    
    
a = [ 1, 2, 3, 1, 2, 1, 1, 1, 2, 3, 5, 6, 3, 4, 5, 2, 4 ]

print (listfreq(a))
def is_numeric_list(x):
    '''
    Function : is_numeric_list(x)
    Description : Checks if a list contains only numbers
    Inputs: List (Simple)
    Output: Boolean
    Usage(print): print (is_numeric_list(a))
    Usage: if not is_number(a) ...
    '''
    
    def is_number(s):
      '''
      Function : is_number
      Description : Checks if a variable is a number
      Inputs : Variable
      Output : Boolean
      Usage : if is_number var ...
      '''
        try:
            float(s) # for int, long and float
        except ValueError:
            try:
                complex(s) # for complex
            except ValueError:
                return False

        return True

    
    for j in x:
        if not is_number(j):
            return False

    return True
def is_empty_list(a):
  '''
  Function : is_empty_list
  Description : Checks if a list is empty
  Inputs: List (Any)
  Output: Boolean
  Usage(print): print (is_empty_list(a))
  Usage: if is_empty_list(a) ...
  '''
    if not a:
        return False
    else:
        return True
def intersect(a, b):
  '''
  Function: intersect_list
  Description: Finds the set intersection between two lists
  Inputs : Two Lists (Any)
  Outputs: One list, the intersection
  Usage(print): print (list_intersect(c1,c2))
  Usage(assign): b = list_intersect(c1,c2))
  '''
  result=[]
  for i in b:
    if isinstance(i,list):
      result.append(intersect(a,i))
    else:
      if i in a:
        result.append(i)
  return result
    
# Example    
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

print (intersect(c1,c2))
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here

def flatten_list(lists):
  '''
  Function : flatten_list
  Description : Converts a list of lists into a list
  Inputs : List of Lists
  Output : List
  Usage(print): print (flatten_list(Lists))
  Usage(Assign): b = flatten_list(Lists))
  '''
    results = []
    for numbers in lists:
        for j in numbers:
            results.append(j)
    return results


print flatten(n)
def find_duplicates_list(x):
  '''
  Function : find_duplicates_list
  Description : Finds and counts all duplicate values
  Inputs : List (Simple)
  Output : Dictionary of duplicate : count
  Usage(print): print (find_duplicates_list(a))
  Usage(Assign): b = find_duplicates_list(a)
  '''
    countdict = dict()
    outdict = dict()
    for j in x:
        if j not in countdict:
            countdict[j] = 1
        else:
            countdict[j] += 1
    for y in countdict.keys():
        if countdict[y] > 1:
            outdict[y] = countdict[y]
    return outdict
    
print (find_duplicates_list(a))
    
def filter_smaller(list, limit):
    
    output = []
    for n in list:
        if n < limit:
            output.append(n)
     
    return output
def filter_larger(list, limit):
    
    output = []
    for n in list:
        if n > limit:
            output.append(n)
     
    return output
def smaller(x,z):
    if x < z:
        return True
    else:
        return False


def larger(x,z):
    if x > z:
        return True
    else:
        return False
def apply_filter_to_list(x,f,limit):
    for item in x[:]: # make a copy of x
        if f(item, limit):
            x.remove(item)
    return x    
        
        
Lista = [ 2, 3, 4, 5, 6, 7, 8 ]
Listb = [ 3, 4, 2, 1, 5, 6, 7 ]
print apply_filter_to_list(Lista, smaller,5)
print apply_filter_to_list(Listb, larger,5)
# Function that counts numbers under a value
def count_smaller(list, limit):
    '''
    Function : Returns the number of elements below a limit
    Inputs   :  List ( List of numbers )
                Limit (Integer or float)
    Returns  : Total number of elements under a value
    Called as : count_smaller(list, limit)
    '''
    total = 0
    for n in list:
        if n < limit:
            total = total + 1
    return total

lost = [4, 8, 15, 16, 23, 42]
small = count_small(lost, 15)
print small
def count_elements(b):
  '''
  Function : count_elements
  Description : Counts elements of a list, converts into dictionary
  Inputs : List (Any)
  Output : Dictionary with frequencies
  Usage(print): print (count_elements(a))
  Usage(Assign): b = count_elements(a)
  '''
    outdict = {}
    for j in b:
        if j not in outdict:
            outdict[j] = 1
        else:
            outdict[j] += 1
    return outdict
def compare(list1, list2):
    '''
    Function : Compare two lists
    Inputs : List1, List2
    Outputs : Tuple of Lists : 
                [0] : Elements that exist in list1 but not in list2
                [1] : Elements that exist in list2 but not in list1
                [2] : Common elements that exist in list1/list2
    Usage : compare(list1, list2)
    Usage (Specific element ) : b = compare(list1, list2)[1]
    '''
    diff1 = [] 
    diff2 = []
    common = []
    for i in list1:
        if i not in list2:
            diff1.append(i) 
        else:
            common.append(i)
        
    for j in list2:
        if j not in list1:
            diff2.append(j)
    
    return ( diff1, diff2, common )
    
    
    
a = [ 1, 2, 3, 4, 5 ]
b = [ 2, 3, 4 ]

print (compare(a,b)[0])
print (compare(a,b)[1])
print (compare(a,b)[2])
print (compare(a,b))
def binarySearch(alist, item):
  '''
  Function: binarySearch
  Description: Binary search on list
  Input: List
  Output: Tuple of boolean, index
  Usage: binarySearch(list, item)
  Notes: Does not edit list in place
  '''
	    if len(alist) == 0:
	        return False
	    else:
	        midpoint = len(alist)//2
	        if alist[midpoint]==item:
	          return (True, midpoint)
	        else:
	          if item<alist[midpoint]:
	            return binarySearch(alist[:midpoint],item)
	          else:
	            return binarySearch(alist[midpoint+1:],item)
	
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binarySearch(testlist, 3))
print(binarySearch(testlist, 13))

# Outside function
# Must return the wanted value
def square(x):
    return x*x


# Test List
lista = [ 1, 2, 3, 4 ]

# Function
def apply_to_list(list,f):
  '''
  Function : apply_to_list
  Called as: apply_to_list(list, function***)
  Description : Applies function to all elements of a list
  Inputs : List / Tuple
  Output : List
  Usage(print): print (apply_to_list(list,f))
  Usage(Assign): b = apply_to_list(list,f)
  '''
    outlist = []
    for i in list:
        outlist.append(f(i))
        
    return outlist
    
print (apply(lista,square))


#########################################

def square(r):
    return r**2

def cube(r):
    return r**3

def filtera(r):
    if r > 2:
        return r 


def applytolist(list, function):
    outlist = []
    for i in list:
        outlist.append(function(i))
    return outlist
    
    
lista = [ 2, 4, 5, 6, 7 ]

print applytolist(lista, square)
print applytolist(lista, cube)        
print applytolist(lista, filtera)

################################
# USING MAP

# Functional programming with map
# Adapted from MIT 6.01 course notes (Section A.2.3)
# http://mit.edu/6.01/mercurial/spring10/www/handouts/readings.pdf

def map(func, lst):
    if lst == []:
        return []
    else:
        return [func(lst[0])] + map(func, lst[1:])
    
def halveElements(lst):
    return map(lambda x: x / 2.0, lst)

def TripleElements(lst):
    return map(lambda x: x * 3.0, lst)
  
input = [2, 4, 6, 8, 10]
output = halveElements(input)
output2 = TripleElements(input)
print (output)
print (output2)
def strtolist(string):
    out = []
    for s in string:
        out.append(s)
    return out
def enqueue(element, list1):
    '''
    Function: enqueue
    Description: Adds an element to a queue (FIFO)
    Input: element, list
    Output: list with added element
    Usage: a = enqueue(element, lista)
    Notes: FIFO = First In, First Out (Oura)
    '''
    list1.append(element)
    return list1
    
def dequeue(list1):
    '''
    Function: dequeue
    Description: Removes first element from queue (FIFO)
    Input: list (queue)
    Output: (newlist, removed element)
    Usage: b = dequeue(list1)
    Notes: FIFO = First In, First Out (Oura)
    
    '''
    b = list1.pop(0)
    return (list1, b)
    
    
a = [ 1,3,5,7]

a = enqueue(10, a)
print (a)

a = dequeue(a)
print (a[0])
print (a[1])
def listtoinfloatstr(list):
  outlist = []
  for j in list:
    # Replace with int or str
    outlist.append(float(j))
def list2tuple(lista):
  '''
  Function : list2tuple
  Description : Converts a list into a tuple
  Inputs : List
  Output : Tuple
  Usage(print): print (list2tuple(list))
  Usage(Assign): b = list2tuple(list))
  '''
    outtup = ()
    for j in lista:
        outtup = outtup + (j,)
        
    return outtup
    
a = [1,2,3,4,5]

print (list2tuple(a))
def count_bigger(list, limit):
    '''
    Function : Returns the number of elements above a limit
    Inputs   :  List ( List of numbers )
                Limit (Integer or float)
    Returns  : Total number of elements above a value
    Called as : count_smaller(list, limit)
    '''
    total = 0
    for n in list:
        if n > limit:
            total = total + 1
    return total

以上是关于python PYTHON_LISTS的主要内容,如果未能解决你的问题,请参考以下文章

001--python全栈--基础知识--python安装

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python