def plot_pop(filename, country_code):

    # Initialize reader object: urb_pop_reader
    urb_pop_reader = pd.read_csv(filename, chunksize=1000)

    # Initialize empty DataFrame: data
    data = pd.DataFrame()
    
    # Iterate over each DataFrame chunk
    for df_urb_pop in urb_pop_reader:
        # Check out specific country: df_pop_ceb
        df_pop_ceb = df_urb_pop[df_urb_pop['CountryCode'] == country_code]

        # Zip DataFrame columns of interest: pops
        pops = zip(df_pop_ceb['Total Population'],
                    df_pop_ceb['Urban population (% of total)'])

        # Turn zip object into list: pops_list
        pops_list = list(pops)

        # Use list comprehension to create new DataFrame column 'Total Urban Population'
        df_pop_ceb['Total Urban Population'] = [int(tup[0] * tup[1]*0.01) for tup in pops_list]
    
        # Append DataFrame chunk to data: data
        data = data.append(df_pop_ceb)

    # Plot urban population data
    data.plot(kind='scatter', x='Year', y='Total Urban Population')
    plt.show()
示例#2
0
def last_n_lines(n):
    with open('sample.txt') as f:
      for line in f:
         line_count += 1
      f.seek(0)
      lines = islice(f, line_count-n, None)
      return list(lines)
示例#3
0
def getRandomCategoryAndPhrase():
    with open("phrases.json", 'r') as f:
        phrases = json.loads(f.read())

        category = random.choice(list(phrases.keys()))
        phrase   = random.choice(phrases[category])
        return (category, phrase.upper())
示例#4
0
>>> def translate(w):
	if w in data:
		return data[w]
	else:
		print("incorrect typed word,did you mean from the following:")
		print(get_close_matches(w,list(data)))
		## for the close matches of the input word
		choose = input("type the correct word from the list:")
		return data[choose.lower()]
示例#5
0
 def threeSum(self, nums):
     from itertools import permutations
     import operator
     from itertools import groupby
     answer=[]
     """
     :type nums: List[int]
     :rtype: List[List[int]]
     """
     self.nums=nums
     if len(self.nums) > 3:
         a = [k for k, v in list(groupby(self.nums))]
         res=list(permutations(a, 3))
         for ele in res:
             if sum(ele) ==0:
                 answer.append(ele)
         return ([k for k, v in groupby(sorted(answer, key=sorted), key=sorted)])
     elif len(self.nums) < 3:
         return []
     else:
         return [self.nums]
示例#6
0
>>> def rotate_string(string, n):
      string = list(string)
      for _ in range(n):
        f = string.pop()
        string.insert(0, f)
      return ''.join(string)
示例#7
0
>>> def _rotate(iterable, n):
      d = deque(iterable)
      for _ in range(n):
        d.rotate()
      return list(d)
示例#8
0
文件: 1.py 项目: woosal1337/Python
    print(cars)


# reversing a list
    # direct reversing, inplace=True:
    cars.reverse()

    # inplace=False reversing:
    cars[::-1]

    # length of a list
    len(cars)


# range and list creations
    random_list = list(range(1,11)) # [1,2,3,4,5,6,7,8,9,10]
    
    numbers = list(range(1,6)) # [1,2,3,4,5]
    even_n = list(range(1,11,2)) # [2,4,6,8,10]
    
    min(random_list) # 1
    max(random_list) # 10
    sum(random_list) # 55


# list comprehensions
    # converting the below code to list comp:
        even_numbers = [] 
        for i in range(11):
           if i % 2 == 0:
               even_numbes.append(i)
示例#9
0
varp[0:3] --> 0 to third index of a tuple
cmp(t1,t2) --> compares elements of both touples
len(touple) --> lenth of the touple
max(touple) min(touple) --> returns item with the max value, or min value
tuple(seq) --> converts a list into a touple
num in (tuple) --> returns boolean if num is in the tubple

--------------------------------------------------------------------------------
GENERATORS
a generator is an iterable object that can be changed by * comprehention functions

[u for u in x if 'temp' in u] --> basic if then generator
(x+1 for x in range(50)) --> 50 times will add 1 to each num of 50
(1 if sen[i]==True else 0 for i in range(len(sen))) 
(fun if eval else fun2 for i in range(50)) --> a generator that acts with true and false evaluaitons
comprehention functions:
list(gen) --> [gen] also works
dict(den)
sum(gen)
----------------------------------------------
strings

r.strip -->, default is whitespace
l.rstrip([]) --> strip off of right side of str


--------------------------------------------------------------------------------
Working with files
with open(...) as f:
var = open('FileName.txt','x') --> x is the opening paramiter
	r; read only, r+; reading and writing (cursor at begenning), w; writing,
	w+; reading and writing (will make new file), a; appending (cursor at end)
示例#10
0
def tail(iterable, n):
    if not isinstance(n, int):
        raise TypeError('Value of N should be Positive Integer')
    if n <=0:
        return []
    return list(iterable)[-n:]
示例#11
0
def get_class_average(students):
    results= list()
    for student in students:
        results.append(get_average(student))
    return average(results)
googol = iter(range(10**100))

# Print the first 5 values from googol
print(next(googol))
print(next(googol))
print(next(googol))
print(next(googol))
print(next(googol))



#------Iterators as function arguments----#

You've been using the iter() function to get an iterator object, as well as the next() function to retrieve the values one by one from the iterator object.

There are also functions that take iterators and iterables as arguments. For example, the list() and sum() functions return a list and the sum of elements, respectively.

In this exercise, you will use these functions by passing an iterable from range() and then printing the results of the function calls.


#Create a range object that would produce the values from 10 to 20 using range(). Assign the result to values.
#Use the list() function to create a list of values from the range object values. Assign the result to values_list.
#Use the sum() function to get the sum of the values from 10 to 20 from the range object values. Assign the result to values_sum.


# Create a range object: values
values = range(10, 21)

# Print the range object
print(values)
示例#13
0
print(len(list))
-> 3

# List Items - Data Types

-> List items can be of any data type.
-> A list with strings, integers and boolean values:

list1 = ["Dhoni", 7, True, 39, "male"]
print(list1)
-> ['Dhoni', 7, True, 39, 'male']

---------------------------------------------------------------------------------------------------

## list() Constructor
-> It is also possible to use the list() 
   constructor when creating a new list.

list = list(("Yuvraj", "Dhoni", "Jadeja"))
# note the double round-brackets
print(list)
-> ['Yuvraj', 'Dhoni', 'Jadeja']

---------------------------------------------------------------------------------------------------

##Access Items
-> List items are indexed and you can access them by referring to the index number:

list = ["Yuvraj", "Dhoni", "Kane Mawa", "David Bhai", "Sam Curran"]

print(list[1]) 
示例#14
0
def loadFile():
with open(&#39;electronics.csv&#39;) as csvfile: #Opens and reads the dataset
reader = csv.reader(csvfile)
data = list(reader)
for x in range(0,len(data)):
del data[x][0] # Removing transaction
Number from the dataset
transactionNumber = len(data) # Counts the number of
lines or number of transactions in a dataset.
return data,transactionNumber
def flatList(currentItemSet): # Function converts Array
of array list into a flat list of data [[1],[2]] =&gt; [1,2]
itemList = [([x] if isinstance(x,str) else x) for x in currentItemSet]
flatList=list(itertools.chain(*itemList)) # Helps in reading entire
string rather than a character from a string.
flatList=set(flatList) # Removes duplicate
elements from the list by using set
flatList=list(flatList) # Converting a SET to LIST
of values.
return flatList
def formatData(data): # Function used to remove
unwanted spaces in the data for a CSV file.
flatList = [item for sublist in data for item in sublist] # converts a
data into flatlist.

while &#39;&#39; in flatList:
flatList.remove(&#39;&#39;)
return flatList
def findSupportItem(supportValue,support,transactionNumber): # Function
identifies the SUPPORT% of each item.
currentItemSet=[]
currentRemoveList=[]

for key, value in supportValue.iteritems(): # Reads a
dictionary list by reading its key and value.
transactionNumber=Decimal(transactionNumber)

if ((value/transactionNumber)*100&gt;=support): #Condition to
check minimum SUPPORT %
finalItemSet[key]=value #Frequent Item
dictionary dataset
currentItemSet.append(key) # Maintains
current item data set.
else:
finalRemoveList[key]=value # Maintains
all remove list dataset
currentRemoveList.append(key) # Current item
remove list.
return finalItemSet,finalRemoveList,currentItemSet,currentRemoveList
def findSupportValue(flatListData): #find the counts of each item
counts=dict(Counter(flatListData)) # Dictionary COUNTER identifies
number of counts for each item.
return counts
def combinationListValue(currentItemSet,x): # Function helps in
identifying combinations of data
combinationList=list(itertools.combinations(currentItemSet,x)) #
Creates a list from COMBINATIONS of data.
return combinationList
def findSupportOccurances(combinationList1,data,supportOccurances): #
Finds the occurrences of subset of data for finding support values.
for x in range(0,len(data)):
for y in range(0,len(combinationList1)):
if (set(combinationList1[y]).issubset(set(data[x]))==True):
#Checks that if the current data is subset of Main Combination list
supportOccurances.append(combinationList1[y])
return supportOccurances
def calculateConfidence(finalSupportSet,confidence,mainKey,subKey): #
Fucntion to calculate % Value of confidence from a set of values.
associationList = [e for e in mainKey if e not in subKey]
if(float(finalSupportSet.get(mainKey))*100/finalSupportSet.get(subKey)&gt;=flo
at(confidence)): #To identify or filter %values with the accepted
confidence.
#print str(subKey) +&#39; -&gt; &#39;+ str(associationList) +&#39;
&#39;+str(float(finalSupportSet.get(mainKey))*100/finalSupportSet.get(subKey))

finalKey=str(subKey) +&#39; -&gt; &#39;+ str(associationList)
# Designing the data based on association rules generated.
finalConfidence=round((finalSupportSet.get(mainKey)/float(finalSupportSet.g
et(subKey)))*100,1) #Gets the data directly from Final frequent dataset
item to calculate the values
finalSupport=round((finalSupportSet.get(mainKey)/float(transactionNumber))*
100,1)
finalList=[]
finalList.append(finalSupport)
finalList.append(finalConfidence)
#Creating final list of support and confidence values.
finalResult[finalKey]=finalList

def findConfindence(finalSupportSet,confidence): # Function to
create confidence sets and identify the confidence values.
finalConfidenceList=dict()
finalSupportList=dict()
for mainKey, mainValue in finalSupportSet.iteritems(): #Iterating
finalSupportItemSet dictionary to identify the confidence.
if not isinstance(mainKey, str):
for subKey,subValue in finalSupportSet.iteritems():
#Iterating finalSupportItemSet dictionary to search for subset values to
identify the confidence,
if isinstance(subKey,str): # To
check identify whether current item is a string or a list &#39;ORANGE&#39; is a
string , [[ORANGE,APPLE]] is a list.
key=[]
key.append(subKey)
subKey=key
if(set(subKey).issubset(set(mainKey))):
calculateConfidence(finalSupportSet,confidence,mainKey,subKey[0])
else:
if(set(subKey).issubset(set(mainKey)) and subKey !=
mainKey): # Identifies the subset values for lists, and identifies
confidence set.
calculateConfidence(finalSupportSet,confidence,mainKey,subKey) # Calling
function to calculate confidence.

if __name__ == &#39;__main__&#39;:
support = input(&quot;Enter % Support\n&quot;) #Enter Support Percentage
(eg:20)
confidence=input(&quot;Enter % Confidence\n&quot;) #Enter Confidence % (eg : 50)
data,transactionNumber=loadFile() # Call function to Load
file
flatListData=formatData(data) # call function to
format Data
supportValue=findSupportValue(flatListData) #Call function identify
the SUPPORT for initial set of data.
itemSet1,removelist1,currentItemSet,currentRemoveList=findSupportItem(suppo
rtValue,support,transactionNumber) #Returning results of current Item
set.
print &quot;\nFREQUENT 1-ITEM SET &quot;
print &quot;``````````````````````&quot;

print str(currentItemSet)+&quot;\n&quot;

x=2
while True:
#Loops until the current frequent items is Zero or Null
currentItemSet=flatList(currentItemSet)
combinationList=combinationListValue(currentItemSet,x)
# Find combination list of item.
supportOccurances=[]
supportOccurances=findSupportOccurances(combinationList,data,supportOccuran
ces) # find the number of occurrences of support
datasets.
counts=findSupportValue(supportOccurances)
finalSupportSet,removelist1,currentItemSet,currentRemoveList=findSupportIte
m(counts,support,transactionNumber) # Returns value of final data set and
current data set.
print &quot;FREQUENT &quot;+str(x)+&quot;-ITEM SET &quot;
print &quot;``````````````````````````&quot;
print str(currentItemSet)+&quot;\n&quot;
if (len(currentItemSet)&lt;=1):
#If currentItemSet has no data or just one data it will exit the loop.
break
x=x+1
print &quot;\nFREQUENT ITEM SETS&quot;
print &quot;````````````````````&quot;
print str(finalSupportSet)+&quot;\n&quot;
findConfindence(finalSupportSet,confidence)
with open(&#39;output.csv&#39;, &#39;w+&#39;) as csvfile: #
Export the results in the csv file.
fieldnames = [&#39;ASSOCIATION RULE&#39;, &#39;SUPPORT&#39;,&#39;CONFIDENCE&#39;] #
Creating title of the csv file.
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
print &quot;\n ASSOCIATION RULE &quot;
print &quot;``````````````````````&quot;

for key,value in finalResult.iteritems():
# Writes finalItemSet results to csv file.
chars_to_remove = [&#39;[&#39;, &#39;]&#39;, &quot;&#39;&quot;]
print key.translate(None, &#39;&#39;.join(chars_to_remove)) + &#39; : &#39; +
str(value)
writer.writerow({&#39;ASSOCIATION RULE&#39;: key.translate(None,
&#39;&#39;.join(chars_to_remove)), &#39;SUPPORT&#39;: value[0],&#39;CONFIDENCE&#39;: value[1]}) #
Writes data to csv file
    )
    dap = OPeNDAP + odp
    dap_urls.extend(dap)

    print("Number of datasets available: {}".format(len(csw.records.keys())))

    for rec, item in csw.records.items():
        print("{}".format(item.title))
    if dap:
        print(fmt(" DAP "))
        for url in dap:
            print("{}.html".format(url))
    print("\n")

# Get only unique endpoints.
dap_urls = list(set(dap_urls))

We found 10 dataset endpoints but only 9 of them have the proper metadata for us to identify the OPeNDAP endpoint,
those that contain either `OPeNDAP:OPeNDAP` or `urn:x-esri:specification:ServiceType:odp:url` scheme.
Unfortunately we lost the `COAWST` model in the process.

The next step is to ensure there are no observations in the list of endpoints.
We want only the models for now.

from ioos_tools.ioos import is_station
from timeout_decorator import TimeoutError

# Filter out some station endpoints.
non_stations = []
for url in dap_urls:
    try:
示例#16
0

>>> l = [1, 2, 3, 4]
1
>>> l = [1, 2, 3, 4]

here each elements in the list is separated by comma and enclosed by a pair of square brackets ( [] ). Elements in the list can be of same type or different type. For e.g:


l2 = ["this is a string", 12]
1
l2 = ["this is a string", 12]
Other ways of creating list.


list1 = list() # Create an empty list
list2 = list([22, 31, 61]) # Create a list with elements 22, 31, 61
list3 = list(["tom", "jerry", "spyke"]) # Create a list with strings
list5 = list("python") # Create a list with characters p, y, t, h, o, n
1
2
3
4
list1 = list() # Create an empty list
list2 = list([22, 31, 61]) # Create a list with elements 22, 31, 61
list3 = list(["tom", "jerry", "spyke"]) # Create a list with strings
list5 = list("python") # Create a list with characters p, y, t, h, o, n

Note: Lists are mutable.

Accessing elements in list
示例#17
0
   constraint. Ranges do support negative indices, but these are
   interpreted as indexing from the end of the sequence determined by
   the positive indices.

   Ranges containing absolute values larger than "sys.maxsize" are
   permitted but some features (such as "len()") may raise
   "OverflowError".

   Range examples:

      >>> list(range(10))
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      >>> list(range(1, 11))
      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      >>> list(range(0, 30, 5))
      [0, 5, 10, 15, 20, 25]
      >>> list(range(0, 10, 3))
      [0, 3, 6, 9]
      >>> list(range(0, -10, -1))
      [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
      >>> list(range(0))
      []
      >>> list(range(1, 0))
      []

   Ranges implement all of the common sequence operations except
   concatenation and repetition (due to the fact that range objects
   can only represent sequences that follow a strict pattern and
   repetition and concatenation will usually violate that pattern).

   start
示例#18
0
class list(object)
 |  list(iterable=(), /)
 |  
示例#19
0
def read_random_line(lineno):
    with open('Data/access-log.txt') as f:
        line = islice(f, lineno, lineno+1)
        return list(line)
# Initialize reader object: urb_pop_reader
urb_pop_reader = pd.read_csv('ind_pop_data.csv', chunksize=1000)

# Get the first DataFrame chunk: df_urb_pop
df_urb_pop = next(urb_pop_reader)

# Check out specific country: df_pop_ceb
df_pop_ceb = df_urb_pop[df_urb_pop['CountryCode'] == 'CEB']

# Zip DataFrame columns of interest: pops
pops = zip(df_pop_ceb['Total Population'], 
            df_pop_ceb['Urban population (% of total)'])

# Turn zip object into list: pops_list
pops_list = list(pops)

# Use list comprehension to create new DataFrame column 'Total Urban Population'
df_pop_ceb['Total Urban Population'] = [int((tup[0]*tup[1])/100) for tup in pops_list]

# Plot urban population data
df_pop_ceb.plot(kind='scatter', x='Year', y='Total Urban Population')
plt.show()

# Use list comprehension to create new DataFrame column 'Total Urban Population'
#df_pop_ceb['Total Urban Population'] = [int(tup/100) for tup in pops_list]

# Plot urban population data
#df_pop_ceb.plot(kind='scatter', x='Year', y='Total Urban Population')
#plt.show()
示例#21
0
    def serverOutdated(self, A):
        # Check if the file doesn't exist
        if not A:
            return -1
       # list of each column
        with open(A, 'r') as file:
            itemList = file.read().splitlines()
            # list of server name
            col1 = []
            # list of Category
            col2 = []
            # list of App Name
            col3 = []
            # list of App Version
            col4 = []

            # split each row in columns
            for item in itemList:
                if item != '':
                    first, second, third, fourth = item.split(',')
                    col1.append(first.strip())
                    col2.append(second.strip())
                    col3.append(third.strip())
                    col4.append(fourth.strip())

            # Unique App
            col3List = list(set(col3))
            # print(col3List)

            # dictionary of apps and their version
            nameVersionList = {}
            for i in range(len(col3List)):

                version = '0'
                for row in range(len(col3)):
                    if col3[row] == col3List[i]:

                        if version < col4[(row)]:
                            version = col4[row]
                            nameVersionList.update({col3List[i] : version})

            # Server name
            serverLowerVersionList = []

            # Older version
            for key, value in nameVersionList.items():
                lowServer = ''
                lowRow = 0
                lowCount = 0

                # count number of the same version
                for row in range(len(col3)):
                    if col3[row] == key:
                        lowCount += 1

                # Multiple apps having older version
                for row in range(len(col3)):
                    if col3[row] == key:
                        if col4[row] != value:
                            serverLowerVersionList.append(col1[row])

                # Unique servers name
            serverLowerVersonUniqueNameList = list(set(serverLowerVersionList))

            for servername in serverLowerVersonUniqueNameList:
                print(servername)
示例#22
0
------
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
First item has index 0 and the last one has index -1.
A list is a collection of items in a particular order. You can make a list that includes the letters of the alphabet, the digits from 0–9, or the names of all the people in your family
In Python, square brackets ([]) indicate a list, and individual elements in the list are separated by commas
Lists are ordered collections, so you can access any element in a list by telling Python the position, or index, of the item desired
By asking for the item at index -1, Python always returns the last item in the list
'''
thislist = ["zaw", "apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist) #['zaw', 'apple', 'banana', 'cherry']
print(thislist[1]) #apple
print(thislist[-1]) #mango
print(thislist[2:5]) #['banana', 'cherry', 'orange']
print(thislist[::-1]) #['mango', 'melon', 'kiwi', 'orange', 'cherry', 'banana', 'apple', 'zaw']
print(reversed(thislist)) #<list_reverseiterator object at 0x01F3A148>
print(list(reversed(thislist))) #['mango', 'melon', 'kiwi', 'orange', 'cherry', 'banana', 'apple', 'zaw']
print(''.join(reversed(thislist))) #mangomelonkiwiorangecherrybananaapplezaw
print(','.join(reversed(thislist))) #mango,melon,kiwi,orange,cherry,banana,apple,zaw
thislist[1] = "blackcurrant" #to change the list
print(thislist) #['zaw', 'blackcurrant', 'banana', 'cherry', 'orange', 'kiwi', 'melon', 'mango']
for x in thislist: #loop the list
  print(x) #Prints one entry per line
for x in thislist:
  print(x,end=",") #zaw,blackcurrant,banana,cherry,orange,kiwi,melon,mango,
if "apple" not in thislist:
    print("YOO !!!") #YOO !!!
print(len(thislist)) #8
thislist.append("orange")
print(thislist) #['zaw', 'blackcurrant', 'banana', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'orange']

thislist=['zaw', 'blackcurrant', 'banana', 'cherry', 'orange', 'kiwi', 'melon', 'mango', 'orange', 345, 56]
   sum = 0
   # use while loop to iterate un till zero
   while(num > 0):
       sum += num
       num -= 1
   print("The sum is",sum)
   
 
 # Change this value for a different result
terms = 10

# Uncomment to take number of terms from user
#terms = int(input("How many terms? "))

# use anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))

# display the result

print("The total terms is:",terms)
for i in range(terms):
   print("2 raised to power",i,"is",result[i])
   
   
 ##Python Program to find numbers divisible by thirteen from a list using anonymous function

# Take a list of numbers
my_list = [12, 65, 54, 39, 102, 339, 221,]

# use anonymous function to filter
result = list(filter(lambda x: (x % 3 == 0), my_list))
示例#24
0
Consider a list (list = []). You can perform the following commands:

insert i e: Insert integer  at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer  at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Initialize your list and read in the value of  followed by  lines of commands where each command will be of the  types listed above. Iterate through each command in order and perform the corresponding operation on your list.

Input Format

The first line contains an integer, , denoting the number of commands.
Each line  of the  subsequent lines contains one of the commands described above.

Constraints

The elements added to the list must be integers.
Output Format

For each command of type print, print the list on a new line.

Sample Input 0

12
insert 0 5
insert 1 10
insert 0 6
print
示例#25
0
list("hello") <------------->   ['h', 'e', 'l', 'l', 'o']      (list casting of string)
list1=['s','h','i','v','a','m']<-----------> "".join(list1) <------->'shivam'     (string casting of list)

Keywords : list() ,tuple()
list=[]
list1=list1()
len(list)
max(list)
min(list)
sum(list)
random.shuffle(list1)   import random

Indexing and Slicing

print(list1[0]) -------First index
print(list1[-1])------Last index
print(list1[:2]) ------before this -------0,1
print(list1[:-2]) ----------after this--------------- -3,-4,-5.......
print(list1[4:6]) --------------  4,5
print(list1[-4:-1])--------- -4,-3,
It can also be used to reverse a list using [::-1]
[::3] it means 'nothing for the first argument, nothing for the second, and jump by three'. It gets every third item of the sequence sliced
list[1::2]  1,3,5....  each +2

names2 = names1 When assigning names1 to names2, we create a second reference to the same list. Changes to names2 affect names1.

names3 = names1[:]  When assigning the slice of all elements in names1 to names3, we are creating a full copy of names1 which can be modified independently. 

list1 = [1, 3, 2], list1 * 2 =[1, 3, 2, 1, 3, 2]
The packages pandas and matplotlib.pyplot have been imported as pd and plt respectively for your use.

Instructions
100 XP
Write a list comprehension to generate a list of values from pops_list for the new column 'Total Urban Population'. The output expression should be the product of the 
first and second element in each tuple in pops_list. Because the 2nd element is a percentage, you also need to either multiply the result by 0.01 or divide it by 100.
In addition, note that the column 'Total Urban Population' should only be able to take on integer values. To ensure this, make sure you cast the output expression to an 
integer with int().
Create a scatter plot where the x-axis are values from the 'Year' column and the y-axis are values from the 'Total Urban Population' column.

----------------------------------------------------------


# Initialize reader object: urb_pop_reader
urb_pop_reader = pd.read_csv('ind_pop_data.csv', chunksize=1000)
# Get the first DataFrame chunk: df_urb_pop
df_urb_pop = next(urb_pop_reader)
# Check out specific country: df_pop_ceb
df_pop_ceb = df_urb_pop[df_urb_pop['CountryCode'] == 'CEB']
# Zip DataFrame columns of interest: pops
pops = zip(df_pop_ceb['Total Population'],
            df_pop_ceb['Urban population (% of total)'])
# Turn zip object into list: pops_list
pops_list = list(pops)
# Use list comprehension to create new DataFrame column 'Total Urban Population'
df_pop_ceb['Total Urban Population'] = [int(tup[0] * tup[1] * 0.01) for tup in pops_list]
# Plot urban population data
df_pop_ceb.plot(kind='scatter', x='Year', y='Total Urban Population')
plt.show()
示例#27
0
Find the length of a dictionary


Iterate through keys and values in dictionaries


test_scores = {"Grace":[80, 72, 90], "Jeffrey":[88, 68, 81], "Sylvia":[80, 82, 84], "Pedro":[98, 96, 95], "Martin":[78, 80, 78], "Dina":[64, 60, 75]}

for student in test_scores.keys():
  print(student)

.keys() method that returns a dict_keys object.
 dict_keys object is a view object, which provides a look at the current state of the dicitonary, without the user being able to modify anything


>>> list(test_scores)
["Grace", "Jeffrey", "Sylvia", "Pedro", "Martin", "Dina"]



.values() method that returns a dict_values object (just like a dict_keys object but for values!)



num_exercises = {"functions": 10, "syntax": 13, "control flow": 15, "loops": 22, "lists": 19, "classes": 18, "dictionaries": 18}

total_exercises = 0

for exercises in num_exercises.values():
  total_exercises += exercises
print(total_exercises)
示例#28
0
 2 8899

 app_list = [1234, 5677, 8899]
 for app_id in iter(app_list):
     print app_id
 输出: 
 1234 
 5677 
 8899


----> @list
@list actually a type, not a function, but the difference isn’t important right  now.
Because strings can’t be modified in the same way as lists, sometimes it can be usef-
ul to create a list from a string. You can do this with the list function:
>>> list('Hello')
['H', 'e', 'l', 'l', 'o']
Note that list works with all kinds of sequences, not just strings. To convert a lis-
t of characters back to a string, you would use the following expression:
''.join(somelist)
where @somelist is your list. 
>>> a=list('hello')
>>> a
['h', 'e', 'l', 'l', 'o']
>>> ''.join(a)
'hello'

1 Changing Lists: Item Assignments
You cannot assign to a position that doesn’t exist;
>>> x = [1, 1, 1]
>>> x[1] = 2 
示例#29
0
1.Write a program to create a list of n integer values and do the following
  Add an item in to the list (using function)
  Delete (using function)
  Store the largest number from the list to a variable
  Store the Smallest number from the list to a variable

2) Create a tuple and print the reverse of the created tuple
3) Create a tuple and convert tuple into list

EXERCISE:1
a=['apple','banana','mango','pear','papaya']
a.append('orange') #adding item using function
print(a)
a.remove(banana) #deleting item using function
print(a)

a=[10,15,25,35,60,75,90]
a.sort()
print("Largest Item in the list is:",a[-1])
print("Smallest Item in the list is:",a[0])

EXERCISE:2
a=['apple','mango','papaya','banana']
b=reversed(a)
print(tuple(b))

EXERCISE:3
a=['banana','apple','orange','pineapple']
b=list(a)
print(b)
示例#30
0
copy()		Returns a copy of the list
count()	Returns the number of elements with the specified value
extend()	Add the elements of a list (or any iterable), to the end of the current list
index()	Returns the index of the first element with the specified value
insert()	Adds an element at the specified position
pop()		Removes the element at the specified position #pop(index no)
remove()	Removes the item with the specified value
reverse()	Reverses the order of the list
sort()		Sorts the list
==================================================
Function	Description
==================================================
all()		Return True if all elements of the list are true (or if the list is empty).
any()		Return True if any element of the list is true. If the list is empty, return False.
enumerate()	Return an enumerate object. It contains the index and value of all the items of list as a tuple.
len()		Return the length (the number of items) in the list.
list()		Convert an iterable (tuple, string, set, dictionary) to a list.
max()		Return the largest item in the list.
min()		Return the smallest item in the list
sorted()	Return a new sorted list (does not sort the list itself).
sum()		Return the sum of all elements in the list.
=============================================
list1 = [1,2,3,4,5,6]
list2 = ["anuj","kumar","aman","anshu"]
list1.append(2) #only one argument
print(list1)
list2.append(10) #string or int, it will take all
print(list2)
#[1, 2, 3, 4, 5, 6, 2]
#['anuj', 'kumar', 'aman', 'anshu', 10]
================================
list1 = [1,2,3,4,5,6]
示例#31
0
44 dir # Function  
45 hasattr # Function  
46 str # Function  
47 repr # Function  

# ------------------------------------------------------- #
'''
A list is a mutable sequence of values of any type.

A list with zero elements is called an empty list.

List elements are indexed by sequential integers, starting with zero.
'''
# ------------------------------------------------------- #
List Constants                                  =       […]
Convert Iterable or Iterator into List          =       list()
Set Value at Specific Position in List          =       a_list[]=
Arithmetic Progressions List                    =       range() 
Add Item to End of List                         =       a_list.append()
Add Multiple Items to End of List               =       a_list.extend()
Insert Item into List                           =       a_list.insert()
Remove Item from List by Value                  =       a_list.remove()
Remove Item from List by Position               =       a_list.pop()
Reverse Items in List                           =       a_list.reverse()
Sort Items in List in Place                     =       a_list.sort()
# ------------------------------------------------------- #
List Constants                                  =       […]

# Syntax:
[val<sub>0</sub>, val<sub>1</sub>, …]
示例#32
0
44 dir # Function
45 hasattr # Function
46 str # Function
47 repr # Function

# ------------------------------------------------------- #
'''
A list is a mutable sequence of values of any type.

A list with zero elements is called an empty list.

List elements are indexed by sequential integers, starting with zero.
'''
# ------------------------------------------------------- #
List Constants                                  =       […]
Convert Iterable or Iterator into List          =       list()
Set Value at Specific Position in List          =       a_list[]=
Arithmetic Progressions List                    =       range()
Add Item to End of List                         =       a_list.append()
Add Multiple Items to End of List               =       a_list.extend()
Insert Item into List                           =       a_list.insert()
Remove Item from List by Value                  =       a_list.remove()
Remove Item from List by Position               =       a_list.pop()
Reverse Items in List                           =       a_list.reverse()
Sort Items in List in Place                     =       a_list.sort()
# ------------------------------------------------------- #
List Constants                                  =       […]

# Syntax:
[val<sub>0</sub>, val<sub>1</sub>, …]
示例#33
0

for i in range(0,len(grocery_list),2):
    print(i,grocert_list[i])

output
0 chicken
2 rice
4 bananas


defitions of range functions
  range(start,end,step)


print(list(range(0,10,3)) )
print(list(range(104,100,-1)) )
print(list(range(5)) )

[0, 3, 6, 9]
[104, 103, 102, 101]
[0, 1, 2, 3, 4]


grocery_list = ['chicken', 'onions', 'rice', 'peppers', 'bananas']
print(grocery_list)
output
['chicken', 'onions', 'rice', 'peppers', 'bananas']
grocery_list[-1] = 'oranges' # replace bananas with oranges
print(grocery_list)
output
示例#34
0
>>> a = [1, 2, 3]
>>> 
>>> b = [4, 5, 6]
>>> 
>>> c = [*a, *b]
>>> c
[1, 2, 3, 4, 5, 6]
>>> 
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]
# Using chain
>>> from itertools import chain
>>> s = chain(a, b)     # Returns an iterator
>>> list(s)
>>> [1, 2, 3, 4, 5, 6]
11. Write program to read a random line in a file. 
ex. 50, 65, 78th line)

from itertools import islice    
def read_random_line(lineno):
    with open('Data/access-log.txt') as f:
        line = islice(f, lineno, lineno+1)
        return list(line)

print(read_random_line(2))
Alternate Solution

def read_random_line(lineno):
    f = open('Data/sample.txt')