【python】ValueError: need more than 0 values to unpack

【python】ValueError: need more than 0 values to unpack,第1张

#coding=utf8

'''

Created on 2014-3-11

@author: NeoWu

'''

def load_data():  

    #指定文件name

    filename_user_movie ='ratings_datatxt'  

    #申明user_movie,为字典 

    user_movie = {}  

    #按行处理ratings_datatxt这个文件

    for line in open(filename_user_movie):  

        #从每行中的内容取三个值userId, itemId, rating,strip()为祛除字符串两头的空格,split()为以空格来分割字符串

        (userId, itemId, rating) = linestrip()split()  

        #将userId的值申明为字典

        user_moviesetdefault(userId,{})  

        #给字典赋值

        user_movie[userId][itemId] = float(rating)  

    return user_movie

print load_data()

运行结果如下:

{'0004': {'03': 212323323}, '0001': {'01': 232323293}, '0002': {'02': 2378323243}, '0003': {'01': 2345232623}}

你运行会出错,应该是你的txt内容不对,其格式应该要类似于这样

 0001  01   232323293

 0002  02   2378323243

 0003  01   2345232623

 0004  03   212323323

>>> c = (('none','aa'),('auto','bb'))

>>> if c[0][0] == 'none':

     print c[0][1]

 

aa

需要安装psutil库

import sys   

import os    

    

import atexit   

import time    

import psutil   

    

#print "Welcome,current system is",osname," 3 seconds late start to get data"       

timesleep(3)   

    

line_num = 1   

    

#function of Get CPU State;   

def getCPUstate(interval=1):   

     return (" CPU: " + str(psutilcpu_percent(interval)) + "%")       

#function of Get Memory       

def getMemorystate():    

         phymem = psutilvirtual_memory()   

         line = "Memory: %5s%% %6s/%s"%(   

             phymempercent,   

             str(int(phymemused/1024/1024))+"M",   

             str(int(phymemtotal/1024/1024))+"M"   

             )   

         return line       

def bytes2human(n):       

         """     

         >>> bytes2human(10000)     

         '98 K'     

         >>> bytes2human(100001221)     

         '954 M'     

         """       

         symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')       

         prefix = {}       

         for i, s in enumerate(symbols):       

                 prefix[s] = 1 << (i+1)10       

         for s in reversed(symbols):       

                 if n >= prefix[s]:       

                         value = float(n) / prefix[s]       

                         return '%2f %s' % (value, s)       

         return '%2f B' % (n)       

          

          

def poll(interval):       

         """Retrieve raw stats within an interval window"""       

         tot_before = psutilnet_io_counters()       

         pnic_before = psutilnet_io_counters(pernic=True)       

         # sleep some time       

         timesleep(interval)       

         tot_after = psutilnet_io_counters()       

         pnic_after = psutilnet_io_counters(pernic=True)       

         # get cpu state       

         cpu_state = getCPUstate(interval)       

         # get memory       

         memory_state = getMemorystate()       

         return (tot_before, tot_after, pnic_before, pnic_after,cpu_state,memory_state)       

          

def refresh_window(tot_before, tot_after, pnic_before, pnic_after,cpu_state,memory_state):       

         if osname == 'nt':   

             ossystem("cls")       

         else:   

             ossystem("clear")       

         """Print stats on screen"""       

          

          

         #print current time #cpu state #memory       

         print(timeasctime()+" | "+cpu_state+" | "+memory_state)       

                  

         # totals       

         print(" NetStates:")       

         print("total bytes:                     sent: %-10s     received: %s" % (bytes2human(tot_afterbytes_sent),       

                                                                                                                                             bytes2human(tot_afterbytes_recv))       

         )       

         print("total packets:                 sent: %-10s     received: %s" % (tot_afterpackets_sent,      

                                                                                                                                             tot_afterpackets_recv)       

         )   

         # per-network interface details: let's sort network interfaces so       

         # that the ones which generated more traffic are shown first       

         print("")       

         nic_names = pnic_afterkeys()       

         #nic_namessort(key=lambda x: sum(pnic_after[x]), reverse=True)       

         for name in nic_names:       

                 stats_before = pnic_before[name]       

                 stats_after = pnic_after[name]       

                 templ = "%-15s %15s %15s"       

                 print(templ % (name, "TOTAL", "PER-SEC"))       

                 print(templ % (       

                         "bytes-sent",       

                         bytes2human(stats_afterbytes_sent),       

                         bytes2human(stats_afterbytes_sent - stats_beforebytes_sent) + '/s',       

                 ))       

                 print(templ % (       

                         "bytes-recv",       

                         bytes2human(stats_afterbytes_recv),       

                         bytes2human(stats_afterbytes_recv - stats_beforebytes_recv) + '/s',       

                 ))       

                 print(templ % (       

                         "pkts-sent",       

                         stats_afterpackets_sent,       

                         stats_afterpackets_sent - stats_beforepackets_sent,       

                 ))       

                 print(templ % (       

                         "pkts-recv",       

                         stats_afterpackets_recv,       

                         stats_afterpackets_recv - stats_beforepackets_recv,       

                 ))       

                 print("")       

          

try:       

         interval = 0       

         while 1:       

                 args = poll(interval)       

                 refresh_window(args)   

                 interval = 1       

except (KeyboardInterrupt, SystemExit):       

         pass

对于你给的字符串,可以被看作一个字典,所以可以按照键值来提取imUrl的value值,也可以用正则表达式提取imUrl的value值

两种方法我都写出来了,你看看吧,要用哪种方法,你自己决定(因为回答问题不能出现链接,所以我把imUrl的value值改成了'imUrl链接',意思是一样的)

第一种方法

data={'asin': '0000037214', 'related': {'also_viewed': ['B00JO8II76', 'B00DGN4R1Q', 'B00E1YRI4C']}, 'title': 'Purple Sequin Tiny Dancer Tutu Ballet Dance Fairy Princess Costume Accessory', 'price': 699, 'salesRank': {'Clothing': 1233557}, 'imUrl': 'imUrl链接', 'brand': 'Big Dreams','categories': [['Clothing, Shoes & Jewelry', 'Girls'], ['Clothing, Shoes & Jewelry', 'Novelty, Costumes & More', 'Costumes & Accessories', 'More Accessories', 'Kids & Baby']]}

print(data['imUrl'])

源代码(注意源代码的缩进)

第二种方法

import re

data="{'asin': '0000037214', 'related': {'also_viewed': ['B00JO8II76', 'B00DGN4R1Q', 'B00E1YRI4C']}, 'title': 'Purple Sequin Tiny Dancer Tutu Ballet Dance Fairy Princess Costume Accessory', 'price': 699, 'salesRank': {'Clothing': 1233557}, 'imUrl': 'imUrl链接', 'brand': 'Big Dreams','categories': [['Clothing, Shoes & Jewelry', 'Girls'], ['Clothing, Shoes & Jewelry', 'Novelty, Costumes & More', 'Costumes & Accessories', 'More Accessories', 'Kids & Baby']]}"

regex = r"'imUrl': '([\s\S]+)'"

match_obj = refindall(regex,data)

for i in range(len(match_obj)):

print(match_obj[i])

源代码(注意源代码的缩进)

以上就是关于【python】ValueError: need more than 0 values to unpack全部的内容,包括:【python】ValueError: need more than 0 values to unpack、python 元祖取值请教、python有没有可以获取每个cpu内核空闲率的等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/9281188.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-26
下一篇 2023-04-26

发表评论

登录后才能评论

评论列表(0条)

保存