简体   繁体   中英

In python, how do I call upon excel sheet column to match a user input?

import pylightxl as xl

with open('city.xlsx', 'rb') as f:
    db = xl.readxl(f)

l = list(db.ws(ws='Sheet1').col(col=3))

cc = input("What is your country code?:  ").upper()

d ={}
for cc in l:
    CC = cc.upper()
    if CC in d:
        d[CC] = d[CC] + 1
    else:
        d[CC] = 1


l2 = list(db.ws(ws='Sheet1').col(col=3)[0:])
matches = 0
for cc in l2:
    if cc == #This is where I want to match the 3 letter Code to Excel
        matches += 1
print("{} Countries match".format(matches)) 

I am currently trying to get the cc = input (max 3 letters) to count any of the matching country codes from the city.xlsx. If I were to input for example AFG into the

if cc = "AFG":

when I run the script I would enter AFG and get a count of the matching country codes, however that only works for the one specific country code, I am wondering how I can make it so that the script can apply to any and all the codes that are within the xlsx file. (The excel file is from the World Database converted to excel)

在此处输入图像描述

You can count the occurences of a value in a list by using the function count(x) from python built-in module collections .

import pylightxl as xl
import collections

with open('city.xlsx', 'rb') as f:
    db = xl.readxl(f)

l = db.ws(ws='Sheet1').col(col=3)

cc = input("What is your country code?:  ").upper()

matches = l.count(cc)

print("{} Countries match".format(matches)) 

# Output:

What is your country code?:   afg
4 Countries match

Note : You don't need to add list() to db.ws(ws='Sheet1').col(col=3) since this one is a list (see here ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM