简体   繁体   中英

Python inquiry I think

没办法,伙计,我怎么能达到那么多字符数?

You can do this:

keys = sorted(data.keys())
print '{0:<10}'.format(''),
for k in keys:
    print '{0:<10}'.format(k),
print
for k in keys:
    print '{0:<10}'.format(k),
    for l in keys:
        print '{0:<10}'.format(data[k].count(l)), 
    print

#            Apple      Banana     Pear      
# Apple      2          4          4         
# Banana     2          5          3         
# Pear       3          2          5

where I used the list's count method to get the counts.

You have a dictionary of list . Iterate over the dictionary and then over the list and collect in a pandas DataFrame and apply a crosstab.

import pandas as pd

df = pandas.DataFrame([
    [col1,col2] for col1, value1 in data.items() for col2 in value1
])

pd.crosstab(df.ix[:,0],df.ix[:,1])

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