python return返回的值为什么总是None

请问下这段代码中,不论把return更换为return 123、return num、return "h"等等,最后打印出的结果都不受return影响,return返回的值总是None

def sum_number(num):

    print(num)
    if num == 1:
        return
        # return 123
        # return num
        # return "h"
    sum_number(num - 1)


print(sum_number(3))

def sum_number(num):

    print(num)
    if num == 1:
        return 123
    sum_number(num - 1)


print(sum_number(3))
def sum_number(num):

    print(num)
    if num == 1:
        return "h"
    sum_number(num - 1)


print(sum_number(3))
def sum_number(num):

    print(num)
    if num == 1:
        return num
    sum_number(num - 1)


print(sum_number(3))

最后的打印结果都是:

3
2
1
None

是我在对比另一段代码:

def sum_numbers(num):

    if num == 1:
        return 1

    temp = sum_numbers(num - 1)

    return num + temp


result = sum_numbers(100)
print(result)

结果:

5050

产生的疑问

1个回答

抱歉,我一开始的回复有问题 。
def sum_number(num):
print(num)
if num == 1:
return 123
else:
k=sum_number(num - 1)
return k

print(sum_number(3))
3
2
1
123

这样就对了!主要是因为递归调用时,k=sum_number(num - 1)会一直不停的运行,需要一个合理的打断跳出,否则函数无合理返回就会显示None。所以递归调用时,条件变换两块都需要return。

Jn0826
記憶‘der 回复wsawsd: 简洁点回答的话就是:1、你先观察原程序,它其实是if : return 1 else: return num+temp的结构;2、你再观察提问者他的程序:它的结构其实是:if :return 123 else: 无return 的结构;3、对于python而言,递归调用如果对于调用自身函数的语句不加return,程序会一直执行调用自身的函数,所以就压根没有返回值。
8 个月之前 回复
wsawsd
wsawsd 您好,可以请问为什么原来程序中,如果是return 123的话,最后打印出的结果不是3 2 1 123呢,return最后不是把函数值返回了吗。像题目中最后累加的程序里,return 1,sum_number(1),打印的结果就是1,而return 2的话,sum_number(1),打印的结果就是2,最后打印的结果是跟着return后面的值来的。
8 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
josephus问题递归求解,函数返回值问题,返回值为none?
# josephus问题递归求解,函数返回值问题 ``` def josephus(args,number):#传入列表和数字 tidailiebiao=[i for i in args]#为了多次调用,使用替代列表 print(tidailiebiao) if(len(tidailiebiao)<number):#递归结束条件 #print(tidailiebiao) #print(len(tidailiebiao)) return tidailiebiao#返回值 else: delete_people=tidailiebiao.pop(number-1)#删除元素 print("remove:%d"%delete_people) tidailiebiao=tidailiebiao[number-1:]+tidailiebiao[:number-1]#生成新列表 josephus(tidailiebiao,number)#递归 test=[i for i in range(1,42)] print(test) print(josephus(test,3))#测试 ``` ![图片说明](https://img-ask.csdn.net/upload/201912/26/1577355089_28075.png) 最后的返回值为none 尝试解决方案,将函数的返回值重新复制给一个新列表,返回新列表,不能解决问题 在函数中加入代码测试发现,当达到返回条件时,返回值不为空 求帮助,多谢各位了
flask响应return时老是报相同的错:TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
flask响应return时老是报相同的错:TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement. python代码为: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200124022917753.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjQ0MTQ3,size_16,color_FFFFFF,t_70) html代码: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200124022948221.png) 奇怪的是另一个与这样相同的响应可以成功跳转,但只有这个不行…… 求助!!!
求助:python爬取12306车票信息总是出现错误
最近初学python,进展到网络爬虫部分,尝试自己写一下查票,结果遇到了麻烦 ``` import requests url = 'https://kyfw.12306.cn/otn/leftTicket/queryZ?' \ 'leftTicketDTO.train_date=2020-02-01&' \ 'leftTicketDTO.from_station=SHH&' \ 'leftTicketDTO.to_station=BJP&purpose_codes=ADULT' result=requests.get(url) print(result.json()) ``` 出现的问题如下: ``` Traceback (most recent call last): File "D:/Files/check tickets/123.py", line 7, in <module> print(result.json()) File "D:\Files\python3\lib\site-packages\requests\models.py", line 897, in json return complexjson.loads(self.text, **kwargs) File "D:\Files\python3\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "D:\Files\python3\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "D:\Files\python3\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ``` 不知如何解决,求解答,谢谢!
简单的Python句式问题
一个程序的返回的值如下 ``` return [None if x is None else x[start:stop] for x in arrays] ``` 返回值是 ``` [array([], shape = (0, 1, 15, 288), dtype = float64)] ``` 其中start = None, stop = None, arrays的形状是(1, 1, 1, 15,288) 为什么返回的值是那样的呢?请大佬指教
python更新pip失败,困扰了我好久
更新pip老是出现下列一大串的文字,我在网上查了许多方法,都没用,有哪位大佬能说一下有什么方法解决这个问题。 这是使用管理员的运行 C:\Windows\system32>python -m pip install --upgrade pip WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/pip/ Collecting pip Downloading https://files.pythonhosted.org/packages/54/0c/d01aa759fdc501a58f431eb594a17495f15b88da142ce14b5845662c13f3/pip-20.0.2-py2.py3-none-any.whl (1.4MB) |█████████████████████▌ | 962kB 2.9kB/s eta 0:02:44ERROR: Exception: Traceback (most recent call last): File "D:\Program Files\python\lib\site-packages\pip\_vendor\urllib3\response.py", line 397, in _error_catcher yield File "D:\Program Files\python\lib\site-packages\pip\_vendor\urllib3\response.py", line 479, in read data = self._fp.read(amt) File "D:\Program Files\python\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 62, in read data = self.__fp.read(amt) File "D:\Program Files\python\lib\http\client.py", line 454, in read n = self.readinto(b) File "D:\Program Files\python\lib\http\client.py", line 498, in readinto n = self.fp.readinto(b) File "D:\Program Files\python\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) File "D:\Program Files\python\lib\ssl.py", line 1241, in recv_into return self.read(nbytes, buffer) File "D:\Program Files\python\lib\ssl.py", line 1099, in read return self._sslobj.read(len, buffer) socket.timeout: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\Program Files\python\lib\site-packages\pip\_internal\cli\base_command.py", line 188, in main status = self.run(options, args) File "D:\Program Files\python\lib\site-packages\pip\_internal\commands\install.py", line 345, in run resolver.resolve(requirement_set) File "D:\Program Files\python\lib\site-packages\pip\_internal\legacy_resolve.py", line 196, in resolve self._resolve_one(requirement_set, req) File "D:\Program Files\python\lib\site-packages\pip\_internal\legacy_resolve.py", line 359, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "D:\Program Files\python\lib\site-packages\pip\_internal\legacy_resolve.py", line 305, in _get_abstract_dist_for abstract_dist = self.preparer.prepare_linked_requirement( File "D:\Program Files\python\lib\site-packages\pip\_internal\operations\prepare.py", line 195, in prepare_linked_requirement unpack_url( File "D:\Program Files\python\lib\site-packages\pip\_internal\download.py", line 1058, in unpack_url unpack_http_url( File "D:\Program Files\python\lib\site-packages\pip\_internal\download.py", line 920, in unpack_http_url from_path, content_type = _download_http_url(link, File "D:\Program Files\python\lib\site-packages\pip\_internal\download.py", line 1152, in _download_http_url _download_url(resp, link, content_file, hashes, progress_bar) File "D:\Program Files\python\lib\site-packages\pip\_internal\download.py", line 861, in _download_url hashes.check_against_chunks(downloaded_chunks) File "D:\Program Files\python\lib\site-packages\pip\_internal\utils\hashes.py", line 75, in check_against_chunks for chunk in chunks: File "D:\Program Files\python\lib\site-packages\pip\_internal\download.py", line 829, in written_chunks for chunk in chunks: File "D:\Program Files\python\lib\site-packages\pip\_internal\utils\ui.py", line 156, in iter for x in it: File "D:\Program Files\python\lib\site-packages\pip\_internal\download.py", line 794, in resp_read for chunk in resp.raw.stream( File "D:\Program Files\python\lib\site-packages\pip\_vendor\urllib3\response.py", line 531, in stream data = self.read(amt=amt, decode_content=decode_content) File "D:\Program Files\python\lib\site-packages\pip\_vendor\urllib3\response.py", line 496, in read raise IncompleteRead(self._fp_bytes_read, self.length_remaining) File "D:\Program Files\python\lib\contextlib.py", line 131, in __exit__ self.gen.throw(type, value, traceback) File "D:\Program Files\python\lib\site-packages\pip\_vendor\urllib3\response.py", line 402, in _error_catcher raise ReadTimeoutError(self._pool, None, 'Read timed out.') pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. WARNING: You are using pip version 19.2.3, however version 20.0.2 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command.
python递归的无法返回或者达到某一条件终止并return
``` class Solution: def canJump(self, nums): if len(nums) == 0: return False def DFS(nums): if len(nums) == 1: return True for i in range(1,nums[0]+1): DFS(nums[i:]) if DFS(nums) is False: print('1111') return True elif DFS(nums) is None: print('2222') return False S =Solution() S.canJump([2,0,0]) ``` 两个问题:1为什么我DFS函数没有返回TRUE ,返回的是None 2如果按照网上的方法在 DFS(nums[i:]) 前加上return 为什么我的i不会循环到2这个值,只能是1就停止了?
关于python函数递归返回值的问题
这是一个匹配字典中词语的函数。 按理说已经匹配成功了 在return之前加个print 输出结果是对的 但是在外面调用输出来就是None 不知道为什么 求大神!! ``` def find_word(dictionary,word): if word in dictionary: return word else: if len(word)-1 == 0: return word else: word = word[0:len(word)-1] find_word(dictionary,word) dictionary = read_dic() print(find_word(dictionary,"热烈欢迎新")) ```
[Python]为什么在win10系统中pip指令用不了?
**哪位大神能帮我解决一下?** 本人还是个小白,所以出现这个错误也不敢妄下断言。 ``` C:\Users\46000>pip Traceback (most recent call last): File "c:\program files\python38\lib\runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\program files\python38\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Program Files\Python38\Scripts\pip.exe\__main__.py", line 9, in <module> TypeError: 'module' object is not callable ``` 为什么'module'对象不可调用? ![图片说明](https://img-ask.csdn.net/upload/202001/06/1578279867_896220.png)
python scrapy 爬虫图片新手求助
求问大神 我这个data她怎么了 报错: 2020-02-07 09:24:55 [scrapy.utils.log] INFO: Scrapy 1.8.0 started (bot: meizitu) 2020-02-07 09:24:55 [scrapy.utils.log] INFO: Versions: lxml 4.5.0.0, libxml2 2.9.5, cssselect 1.1.0, parsel 1.5.2, w3lib 1.21.0, Twisted 19.10.0, Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)], pyOpenSSL 19.1.0 (OpenSSL 1.1.1d 10 Sep 2019), cryptography 2.8, Platform Windows-10-10.0.17763-SP0 2020-02-07 09:24:55 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'meizitu', 'NEWSPIDER_MODULE': 'meizitu.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['meizitu.spiders']} 2020-02-07 09:24:55 [scrapy.extensions.telnet] INFO: Telnet Password: 0936097982b9bcc8 2020-02-07 09:24:55 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.logstats.LogStats'] 2020-02-07 09:24:56 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware', 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2020-02-07 09:24:56 [scrapy.middleware] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] Unhandled error in Deferred: 2020-02-07 09:24:56 [twisted] CRITICAL: Unhandled error in Deferred: Traceback (most recent call last): File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 184, in crawl return self._crawl(crawler, *args, **kwargs) File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 188, in _crawl d = crawler.crawl(*args, **kwargs) File "e:\python3.7\lib\site-packages\twisted\internet\defer.py", line 1613, in unwindGenerator return _cancellableInlineCallbacks(gen) File "e:\python3.7\lib\site-packages\twisted\internet\defer.py", line 1529, in _cancellableInlineCallbacks _inlineCallbacks(None, g, status) --- <exception caught here> --- File "e:\python3.7\lib\site-packages\twisted\internet\defer.py", line 1418, in _inlineCallbacks result = g.send(result) File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 86, in crawl self.engine = self._create_engine() File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 111, in _create_engine return ExecutionEngine(self, lambda _: self.stop()) File "e:\python3.7\lib\site-packages\scrapy\core\engine.py", line 70, in __init__ self.scraper = Scraper(crawler) File "e:\python3.7\lib\site-packages\scrapy\core\scraper.py", line 71, in __init__ self.itemproc = itemproc_cls.from_crawler(crawler) File "e:\python3.7\lib\site-packages\scrapy\middleware.py", line 53, in from_crawler return cls.from_settings(crawler.settings, crawler) File "e:\python3.7\lib\site-packages\scrapy\middleware.py", line 34, in from_settings mwcls = load_object(clspath) File "e:\python3.7\lib\site-packages\scrapy\utils\misc.py", line 46, in load_object mod = import_module(module) File "e:\python3.7\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed builtins.SyntaxError: unexpected EOF while parsing (pipelines.py, line 22) 2020-02-07 09:24:56 [twisted] CRITICAL: Traceback (most recent call last): File "e:\python3.7\lib\site-packages\twisted\internet\defer.py", line 1418, in _inlineCallbacks result = g.send(result) File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 86, in crawl self.engine = self._create_engine() File "e:\python3.7\lib\site-packages\scrapy\crawler.py", line 111, in _create_engine return ExecutionEngine(self, lambda _: self.stop()) File "e:\python3.7\lib\site-packages\scrapy\core\engine.py", line 70, in __init__ self.scraper = Scraper(crawler) File "e:\python3.7\lib\site-packages\scrapy\core\scraper.py", line 71, in __init__ self.itemproc = itemproc_cls.from_crawler(crawler) File "e:\python3.7\lib\site-packages\scrapy\middleware.py", line 53, in from_crawler return cls.from_settings(crawler.settings, crawler) File "e:\python3.7\lib\site-packages\scrapy\middleware.py", line 34, in from_settings mwcls = load_object(clspath) File "e:\python3.7\lib\site-packages\scrapy\utils\misc.py", line 46, in load_object mod = import_module(module) File "e:\python3.7\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "E:\python_work\爬虫\meizitu\meizitu\pipelines.py", line 22 f.write(data) ^ SyntaxError: unexpected EOF while parsing 代码如下: pipeline ``` import requests class MeizituPipeline(object): def process_item(self, item, spider): print("main_title:",item['main_title']) print("main_image:", item['main_image']) print("main_tags:", item['main_tags']) print("main_meta:", item['main_meta']) print("page:", item['main_pagenavi']) url = requests.get(item['main_image']) print(url) try: with open(item['main_pagenavi'] +'.jpg','wb') as f: data = url.read() f.write(data) ``` image.py ``` import scrapy from scrapy.http import response from ..items import MeizituItem class ImageSpider(scrapy.Spider): #定义Spider的名字scrapy crawl meiaitu name = 'SpiderMain' #允许爬虫的域名 allowed_domains = ['www.mzitu.com/203554'] #爬取的首页列表 start_urls = ['https://www.mzitu.com/203554'] #负责提取response的信息 #response代表下载器从start_urls中的url的到的回应 #提取的信息 def parse(self,response): #遍历所有节点 for Main in response.xpath('//div[@class = "main"]'): item = MeizituItem() #匹配所有节点元素/html/body/div[2]/div[1]/div[3]/p/a content = Main.xpath('//div[@class = "content"]') item['main_title'] = content.xpath('./h2/text()') item['main_image'] = content.xpath('./div[@class="main-image"]/p/a/img') item['main_meta'] = content.xpath('./div[@class="main-meta"]/span/text()').extract() item['main_tags'] = content.xpath('./div[@class="main-tags"]/a/text()').extract() item['main_pagenavi'] = content.xpath('./div[@class="main_pagenavi"]/span/text()').extract_first() yield item new_links = response.xpath('.//div[@class="pagenavi"]/a/@href').extract() new_link =new_links[-1] yield scrapy.Request(new_link,callback=self.parse) ``` setting ``` BOT_NAME = 'meizitu' SPIDER_MODULES = ['meizitu.spiders'] NEWSPIDER_MODULE = 'meizitu.spiders' ROBOTSTXT_OBEY = True #配置默认请求头 DEFAULT_REQUEST_HEADERS = { "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36", 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' } ITEM_PIPELINES = { 'meizitu.pipelines.MeizituPipeline':300, } IMAGES_STORE = 'E:\python_work\爬虫\meizitu' IMAGES_MIN_HEIGHT = 1050 IMAGES_MIN_WIDTH = 700 ```
问个有关python+django+heroku的问题
``` Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/app/learning_logs/models.py", line 7, in <module> class Topic(models.Model): File "/app/learning_logs/models.py", line 8, in Topic choices=Help().choices() File "/app/learning_logs/help.py", line 9, in choices for user in users: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 658, in reraise raise value.with_traceback(tb) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... ``` 在heroku bash操作makemigrations,migrate中出现的错误 在本地用这些没问题 settings.py ``` """ Django settings for learning_log project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'o47!#$sbu_&=)pnbk63ra!hjbx@+pc=2j42cf(&mx82&hs&ph_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my app 'learning_logs', 'users', #other app 'bootstrap3', ) MIDDLEWARE = [ 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'learning_log.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'learning_log.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_URL = '/users/login/' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if os.getenv('DATABASE_URL') is not None: import dj_database_url DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['stark-anchorage-08076.herokuapp.com'] DEBUG = False BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) django_heroku.settings(locals()) ``` views.py ``` from django.shortcuts import render from .models import Topic, Entry, Root, Suf_Pre_fix from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from .forms import TopicForm, EntryForm, RootForm from django.contrib.auth.decorators import login_required from .help import Help from django.contrib.auth.models import User # Create your views here. def index(request): return render(request, 'learning_logs/index.html') @login_required def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic,'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.edit_able = request.POST.getlist("edit_able") new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form, 'users':Help().users()} return render(request, 'learning_logs/new_topic.html', context) @login_required def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.edit_able = request.POST.getlist("edit_able") new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic_id])) context = {'topic':topic, 'form': form, 'users':Help().users()} return render(request, 'learning_logs/new_entry.html', context) @login_required def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if not Help().check_user(request.user,entry.edit_able) or not Help().check_user(request.user,topic.edit_able): raise Http404 if request.method != 'POST': form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): edit_entry = form.save(commit=False) edit_entry.edit_able = request.POST.getlist("edit_able") edit_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic',args=[topic.id])) context = {'entry': entry, 'topic': topic, 'form': form ,'users':Help().users()} return render(request, 'learning_logs/edit_entry.html', context) @login_required def roots(request): roots = Root.objects.order_by('date_added') context = {'roots': roots} return render(request, 'learning_logs/roots.html', context) def root(request, root_id): root = Root.objects.get(id=root_id) things = root.things.order_by('-date_added') context = {'root':root, 'things':things} return render(request, 'learning_logs/root.html', context) ``` help.py ``` from django.contrib.auth.models import User class Help(): def __init__(self): pass def choices(self): users=User.objects.all() choices=[] a=1 for user in users: choices.append((a,str(user))) a+=1 return choices def check_user(self,user,users): try: str(users).index(str(user)) except: return False else: return True def users(self): users=[] for user in User.objects.all(): users.append(str(user)) return users def test_list(self,list1): for item in list1: print(type(item)) def test_word(self,item): print(item,type(item)) ```
python 安装 pymssql 库时报错
安装第三方库 ``` pip install pymssql Traceback (most recent call last): File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_vendor\urllib3\response.py", line 425, in _error_catcher yield File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_vendor\urllib3\response.py", line 507, in read data = self._fp.read(amt) if not fp_closed else b"" File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 62, in read data = self.__fp.read(amt) File "c:\users\XXX\appdata\local\programs\python\python37\lib\http\client.py", line 457, in read n = self.readinto(b) File "c:\users\XXX\appdata\local\programs\python\python37\lib\http\client.py", line 501, in readinto n = self.fp.readinto(b) File "c:\users\XXX\appdata\local\programs\python\python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) File "c:\users\XXX\appdata\local\programs\python\python37\lib\ssl.py", line 1071, in recv_into return self.read(nbytes, buffer) File "c:\users\XXX\appdata\local\programs\python\python37\lib\ssl.py", line 929, in read return self._sslobj.read(len, buffer) socket.timeout: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\cli\base_command.py", line 153, in _main status = self.run(options, args) File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\commands\install.py", line 382, in run resolver.resolve(requirement_set) File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\legacy_resolve.py", line 201, in resolve self._resolve_one(requirement_set, req) File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\legacy_resolve.py", line 365, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\legacy_resolve.py", line 313, in _get_abstract_dist_for req, self.session, self.finder, self.require_hashes File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\operations\prepare.py", line 194, in prepare_linked_requirement progress_bar=self.progress_bar File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\download.py", line 465, in unpack_url progress_bar=progress_bar File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\download.py", line 316, in unpack_http_url progress_bar) File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\download.py", line 551, in _download_http_url _download_url(resp, link, content_file, hashes, progress_bar) File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\download.py", line 253, in _download_url hashes.check_against_chunks(downloaded_chunks) File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\utils\hashes.py", line 80, in check_against_chunks for chunk in chunks: File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\download.py", line 223, in written_chunks for chunk in chunks: File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\utils\ui.py", line 160, in iter for x in it: File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_internal\download.py", line 212, in resp_read decode_content=False): File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_vendor\urllib3\response.py", line 564, in stream data = self.read(amt=amt, decode_content=decode_content) File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_vendor\urllib3\response.py", line 529, in read raise IncompleteRead(self._fp_bytes_read, self.length_remaining) File "c:\users\XXX\appdata\local\programs\python\python37\lib\contextlib.py", line 130, in __exit__ self.gen.throw(type, value, traceback) File "c:\users\XXX\appdata\local\programs\python\python37\lib\site-packages\pip\_vendor\urllib3\response.py", line 430, in _error_catcher raise ReadTimeoutError(self._pool, None, "Read timed out.") pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='pypi.tuna.tsinghua.edu.cn', port=443): Read timed out. ``` 也下载了 wordcloud-1.6.0-cp37-cp37m-win_amd64.whl python版本是3.7 64位
python pd.merge()合并后的DataFrame无法输出到excel表
代码: import pandas as pd from pandas import DataFrame df3 = DataFrame({'key1': ['one', 'two', 'three', 'two'], 'key2': ['two', 'three', 'one', 'one'], 'data': [1, 2, 3, 4]}) df4 = DataFrame({'key1': ['two', 'two', 'three'], 'key2': ['one', 'two', 'one'], 'data': [1, 2, 3]}) data = pd.merge(df3, df4, on=['key1', 'key2'], how='outer') print(data) data.to_excel('D:\01.xls', na_rep=None) 结果: key1 key2 data_x data_y 0 one two 1.0 NaN 1 two three 2.0 NaN 2 three one 3.0 3.0 3 two one 4.0 1.0 4 two two NaN 2.0 Traceback (most recent call last): File "D:/python项目/02.py", line 232, in <module> data.to_excel('D:\01.xls', na_rep=None) File "F:\python\lib\site-packages\pandas\core\generic.py", line 2256, in to_excel engine=engine, File "F:\python\lib\site-packages\pandas\io\formats\excel.py", line 742, in write writer.save() File "F:\python\lib\site-packages\pandas\io\excel\_xlwt.py", line 32, in save return self.book.save(self.path) File "F:\python\lib\site-packages\xlwt\Workbook.py", line 710, in save doc.save(filename_or_stream, self.get_biff_data()) File "F:\python\lib\site-packages\xlwt\CompoundDoc.py", line 262, in save f = open(file_name_or_filelike_obj, 'w+b') OSError: [Errno 22] Invalid argument: 'D:\x01.xls' 为什么会报错呢?两个DataFrame使用merge方法合并后不是变成一个DataFrame了吗,为什么使用to_excel方法会出现错误?
python类内部的方法调用
class Adaboosting中demo_train方法中要调用同个类中的loadDataSet方法,但是根本没进到程序之中,求教是什么原因,谢谢大佬们了 demo_train的代码如下 ``` def demo_train(self): print("已进入到了内部函数") print(self.model) if self.model==None: self.model="test.txt" dataArr, LabelArr = self.loadDataSet(self.model) weakClassArr, aggClassEst = Adaboosting.adaBoostTrainDS(dataArr, LabelArr) # from my_adaboosting_SVM_ROC import adaClassify print("正在训练模型...") predictions = self.adaClassify(dataArr, weakClassArr) errArr = np.mat(np.ones((len(dataArr), 1))) number=1-float(errArr[predictions != np.mat(LabelArr).T].sum() / len(dataArr) * 100) print('训练集的错误率:%.3f%%' % float(errArr[predictions != np.mat(LabelArr).T].sum() / len(dataArr) * 100)) # print("33333333") print(self.train) if self.train==None: self.train="test6.txt" # print("444444444") print(self.train) # train = "test6.txt" testArr, testLabelArr = self.loadDataSet(self.train) predictions = self.adaClassify(testArr, weakClassArr) print(predictions) errArr = np.mat(np.ones((len(testArr), 1))) number1=1-float(errArr[predictions != np.mat(testLabelArr).T].sum() / len(testArr) * 100) print('测试集的错误率:%.3f%%' % float(errArr[predictions != np.mat(testLabelArr).T].sum() / len(testArr) * 100)) from my_adaboosting_SVM_ROC import plotROC plotROC(aggClassEst.T, LabelArr) return number ,number1 ``` loadDataSet的代码如下 ``` # 导入数据 def loadDataSet(fileName): print("hhhhhhhhhhhhhhhhh") numFeat = len((open(fileName).readline().split('\t'))) dataMat = []; labelMat = [] fr = open(fileName) for line in fr.readlines(): lineArr = [] curLine = line.strip().split('\t') for i in range(numFeat - 1): lineArr.append(float(curLine[i])) dataMat.append(lineArr) labelMat.append(float(curLine[-1])) return dataMat, labelMat ``` 运行结果: ![图片说明](https://img-ask.csdn.net/upload/202001/12/1578831845_541963.png)
tensorflow 训练数据集时,报错InvalidArgumentError: Incompatible shapes: [15] vs. [15,6],标签的占位符与标签喂的数据格式不符,要怎么解决?
InvalidArgumentError (see above for traceback): Incompatible shapes: [15] vs. [15,6] 报错的详细信息如下所示: ``` INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.CancelledError'>, Enqueue operation was cancelled [[Node: input_producer/input_producer_EnqueueMany = QueueEnqueueManyV2[Tcomponents=[DT_STRING], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input_producer, input_producer/RandomShuffle)]] Caused by op 'input_producer/input_producer_EnqueueMany', defined at: File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel_launcher.py", line 16, in <module> app.launch_new_instance() File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance app.start() File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelapp.py", line 477, in start ioloop.IOLoop.instance().start() File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start super(ZMQIOLoop, self).start() File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tornado\ioloop.py", line 888, in start handler_func(fd_obj, events) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events self._handle_recv() File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv self._run_callback(callback, msg) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback callback(*args, **kwargs) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 283, in dispatcher return self.dispatch_shell(stream, msg) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 235, in dispatch_shell handler(stream, idents, msg) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 399, in execute_request user_expressions, allow_stdin) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute res = shell.run_cell(code, store_history=store_history, silent=silent) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\zmqshell.py", line 533, in run_cell return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2698, in run_cell interactivity=interactivity, compiler=compiler, result=result) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2802, in run_ast_nodes if self.run_code(code, result): File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-19-6fa659dba762>", line 320, in <module> batch_test(data_path, 100, 100, n_batch, train_op, loss, acc, range_num, val_batch) File "<ipython-input-19-6fa659dba762>", line 147, in batch_test tf_image,tf_label = read_records(record_file,resize_height,resize_width,type='normalization') File "<ipython-input-19-6fa659dba762>", line 84, in read_records filename_queue = tf.train.string_input_producer([filename]) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\training\input.py", line 232, in string_input_producer cancel_op=cancel_op) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\training\input.py", line 164, in input_producer enq = q.enqueue_many([input_tensor]) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\data_flow_ops.py", line 367, in enqueue_many self._queue_ref, vals, name=scope) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\gen_data_flow_ops.py", line 1556, in _queue_enqueue_many_v2 name=name) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op op_def=op_def) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op original_op=self._default_original_op, op_def=op_def) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__ self._traceback = _extract_stack() CancelledError (see above for traceback): Enqueue operation was cancelled [[Node: input_producer/input_producer_EnqueueMany = QueueEnqueueManyV2[Tcomponents=[DT_STRING], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input_producer, input_producer/RandomShuffle)]] --------------------------------------------------------------------------- InvalidArgumentError Traceback (most recent call last) H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args) 1038 try: -> 1039 return fn(*args) 1040 except errors.OpError as e: H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata) 1020 feed_dict, fetch_list, target_list, -> 1021 status, run_metadata) 1022 H:\aa\Anaconda\anaconda\envs\tensorflow\lib\contextlib.py in __exit__(self, type, value, traceback) 87 try: ---> 88 next(self.gen) 89 except StopIteration: H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\errors_impl.py in raise_exception_on_not_ok_status() 465 compat.as_text(pywrap_tensorflow.TF_Message(status)), --> 466 pywrap_tensorflow.TF_GetCode(status)) 467 finally: InvalidArgumentError: Incompatible shapes: [15] vs. [15,6] [[Node: Equal = Equal[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](Cast_1, _recv_y__0/_21)]] [[Node: Mean/_25 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_177_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]] During handling of the above exception, another exception occurred: InvalidArgumentError Traceback (most recent call last) <ipython-input-19-6fa659dba762> in <module>() 318 range_num = 5 319 --> 320 batch_test(data_path, 100, 100, n_batch, train_op, loss, acc, range_num, val_batch) 321 <ipython-input-19-6fa659dba762> in batch_test(record_file, resize_height, resize_width, n_batch, train_op, loss, acc, range_num, val_batch) 187 images_x = np.reshape(images, (-1, 30000)) 188 labels_y = np.reshape(labels, (-1, 6)) --> 189 _,err,ac = sess.run([train_op,loss,acc],feed_dict={x:images, y_:labels_y}) # 50% 神经元在工作中 190 train_loss = train_loss + err 191 train_acc = train_acc + ac H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata) 776 try: 777 result = self._run(None, fetches, feed_dict, options_ptr, --> 778 run_metadata_ptr) 779 if run_metadata: 780 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata) 980 if final_fetches or final_targets: 981 results = self._do_run(handle, final_targets, final_fetches, --> 982 feed_dict_string, options, run_metadata) 983 else: 984 results = [] H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata) 1030 if handle is None: 1031 return self._do_call(_run_fn, self._session, feed_dict, fetch_list, -> 1032 target_list, options, run_metadata) 1033 else: 1034 return self._do_call(_prun_fn, self._session, handle, feed_dict, H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args) 1050 except KeyError: 1051 pass -> 1052 raise type(e)(node_def, op, message) 1053 1054 def _extend_graph(self): InvalidArgumentError: Incompatible shapes: [15] vs. [15,6] [[Node: Equal = Equal[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](Cast_1, _recv_y__0/_21)]] [[Node: Mean/_25 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_177_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]] Caused by op 'Equal', defined at: File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel_launcher.py", line 16, in <module> app.launch_new_instance() File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance app.start() File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelapp.py", line 477, in start ioloop.IOLoop.instance().start() File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start super(ZMQIOLoop, self).start() File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tornado\ioloop.py", line 888, in start handler_func(fd_obj, events) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events self._handle_recv() File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv self._run_callback(callback, msg) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback callback(*args, **kwargs) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 283, in dispatcher return self.dispatch_shell(stream, msg) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 235, in dispatch_shell handler(stream, idents, msg) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\kernelbase.py", line 399, in execute_request user_expressions, allow_stdin) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute res = shell.run_cell(code, store_history=store_history, silent=silent) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\ipykernel\zmqshell.py", line 533, in run_cell return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2698, in run_cell interactivity=interactivity, compiler=compiler, result=result) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2802, in run_ast_nodes if self.run_code(code, result): File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-19-6fa659dba762>", line 311, in <module> correct_prediction = tf.equal(tf.cast(tf.argmax(logits,1),tf.float32), y_) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 672, in equal result = _op_def_lib.apply_op("Equal", x=x, y=y, name=name) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op op_def=op_def) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op original_op=self._default_original_op, op_def=op_def) File "H:\aa\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__ self._traceback = _extract_stack() InvalidArgumentError (see above for traceback): Incompatible shapes: [15] vs. [15,6] [[Node: Equal = Equal[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](Cast_1, _recv_y__0/_21)]] [[Node: Mean/_25 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_177_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]] ``` x,y- 占位符打印的信息如下: ``` x: Tensor("x-input:0", shape=(?, 100, 100, 3), dtype=float32) y_:Tensor("y_:0", shape=(?, 6), dtype=float32) ``` image 和 labels 的打印信息如下: ``` shape:(15, 100, 100, 3),tpye:float32,labels:[[ 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 1. 0. 0.] [ 0. 0. 0. 0. 1. 0.] [ 1. 0. 0. 0. 0. 0.] [ 0. 0. 0. 1. 0. 0.] [ 1. 0. 0. 0. 0. 0.] [ 1. 0. 0. 0. 0. 0.] [ 1. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 1.] [ 0. 0. 1. 0. 0. 0.] [ 1. 0. 0. 0. 0. 0.] [ 1. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 1. 0.] [ 0. 0. 0. 0. 1. 0.]] ``` 整个运行的代码如下: ``` import tensorflow as tf import numpy as np import os import cv2 import matplotlib.pyplot as plt import random import time from PIL import Image os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' data_path = 'people_pictures_train/record/one_train_demo_people_train.tfrecords' # tfrecords 文件的地址 data_path_val = 'people_pictures_train/record/one_test_demo_people_val.tfrecords' # tfrecords 文件的地址 print("----------------------------") tf.reset_default_graph() def get_example_nums(tf_records_filenames): ''' 统计tf_records图像的个数(example)个数 :param tf_records_filenames: tf_records文件路径 :return: ''' nums= 0 for record in tf.python_io.tf_record_iterator(tf_records_filenames): nums += 1 return nums def show_image(title,image): ''' 显示图片 :param title: 图像标题 :param image: 图像的数据 :return: ''' # plt.figure("show_image") # print(image.dtype) plt.imshow(image) plt.axis('on') # 关掉坐标轴为 off plt.title(title) # 图像题目 plt.show() def get_batch_images(images,labels,batch_size,labels_nums,one_hot=False,shuffle=False,num_threads=1): ''' :param images:图像 :param labels:标签 :param batch_size: :param labels_nums:标签个数 :param one_hot:是否将labels转为one_hot的形式 :param shuffle:是否打乱顺序,一般train时shuffle=True,验证时shuffle=False :return:返回batch的images和labels ''' min_after_dequeue = 200 capacity = min_after_dequeue + 3 * batch_size # 保证capacity必须大于min_after_dequeue参数值 if shuffle: images_batch, labels_batch = tf.train.shuffle_batch([images,labels], batch_size=batch_size, capacity=capacity, min_after_dequeue=min_after_dequeue, num_threads=num_threads) else: images_batch, labels_batch = tf.train.batch([images,labels], batch_size=batch_size, capacity=capacity, num_threads=num_threads) if one_hot: labels_batch = tf.one_hot(labels_batch, labels_nums, 1, 0) return images_batch,labels_batch def read_records(filename,resize_height, resize_width,type=None): ''' 解析record文件:源文件的图像数据是RGB,uint8,[0,255],一般作为训练数据时,需要归一化到[0,1] :param filename: :param resize_height: :param resize_width: :param type:选择图像数据的返回类型 None:默认将uint8-[0,255]转为float32-[0,255] normalization:归一化float32-[0,1] standardization:归一化float32-[0,1],再减均值中心化 :return: ''' # 创建文件队列,不限读取的数量 filename_queue = tf.train.string_input_producer([filename]) # create a reader from file queue reader = tf.TFRecordReader() # reader从文件队列中读入一个序列化的样本 _, serialized_example = reader.read(filename_queue) # get feature from serialized example # 解析符号化的样本 features = tf.parse_single_example( serialized_example, features={ 'image_raw': tf.FixedLenFeature([], tf.string), 'height': tf.FixedLenFeature([], tf.int64), 'width': tf.FixedLenFeature([], tf.int64), 'depth': tf.FixedLenFeature([], tf.int64), 'labels': tf.FixedLenFeature([], tf.string) } ) tf_image = tf.decode_raw(features['image_raw'], tf.uint8)#获得图像原始的数据 tf_height = features['height'] tf_width = features['width'] tf_depth = features['depth'] # tf_label = tf.cast(features['labels'], tf.float32) tf_label = tf.decode_raw(features['labels'],tf.float32) # PS:恢复原始图像数据,reshape的大小必须与保存之前的图像shape一致,否则出错 # tf_image=tf.reshape(tf_image, [-1]) # 转换为行向量 tf_image=tf.reshape(tf_image, [resize_height, resize_width, 3]) # 设置图像的维度 tf_label=tf.reshape(tf_label, [6]) # 设置图像的维度 # 恢复数据后,才可以对图像进行resize_images:输入uint->输出float32 # tf_image=tf.image.resize_images(tf_image,[224, 224]) # [3]数据类型处理 # 存储的图像类型为uint8,tensorflow训练时数据必须是tf.float32 if type is None: tf_image = tf.cast(tf_image, tf.float32) elif type == 'normalization': # [1]若需要归一化请使用: # 仅当输入数据是uint8,才会归一化[0,255] # tf_image = tf.cast(tf_image, dtype=tf.uint8) # tf_image = tf.image.convert_image_dtype(tf_image, tf.float32) tf_image = tf.cast(tf_image, tf.float32) * (1. / 255.0) # 归一化 elif type == 'standardization': # 标准化 # tf_image = tf.cast(tf_image, dtype=tf.uint8) # tf_image = tf.image.per_image_standardization(tf_image) # 标准化(减均值除方差) # 若需要归一化,且中心化,假设均值为0.5,请使用: tf_image = tf.cast(tf_image, tf.float32) * (1. / 255) - 0.5 # 中心化 # 这里仅仅返回图像和标签 # return tf_image, tf_height,tf_width,tf_depth,tf_label return tf_image,tf_label def batch_test(record_file,resize_height,resize_width,n_batch,train_op,loss,acc,range_num,val_batch): ''' :param record_file: record文件路径 :param resize_height: :param resize_width: :return: :PS:image_batch, label_batch一般作为网络的输入 ''' # 读取record函数 tf_image,tf_label = read_records(record_file,resize_height,resize_width,type='normalization') image_batch, label_batch= get_batch_images(tf_image,tf_label,batch_size=15,labels_nums=6,one_hot=False,shuffle=True) a = image_batch.get_shape() a2 = a.as_list() b = label_batch.get_shape() b2 = b.as_list() print('image_batch: '+ str(image_batch) + ' label_batch: ' + str(label_batch)) print('image_batch-len:' + str(len(a2)) + ' label_batch-len: ' + str(len(b2))) # 测试的数据 images_val,labels_val = read_records(data_path_val,100,100,type='normalization') image_batch_val, label_batch_val = get_batch_images(images_val,labels_val,batch_size=15,labels_nums=6,one_hot=False,shuffle=True) # print('image_batch_val: '+ str(image_batch_val) + ' label_batch_val: ' + str(label_batch_val)) init = tf.global_variables_initializer() with tf.Session() as sess: # 开始一个会话 sess.run(init) # train_writer = tf.summary.FileWriter('logs/train',sess.graph) # 当前目录下的 logs 文件夹,如果没有这个文件夹,会自己键, 写入graph 的图 # test_writer = tf.summary.FileWriter('logs/test',sess.graph) # 当前目录下的 logs 文件夹,如果没有这个文件夹,会自己键, 写入graph 的图 coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for epoch in range(range_num) : start_time = time.time() train_loss, train_acc = 0,0 for i in range(n_batch): images, labels = sess.run([image_batch, label_batch]) print('shape:{},tpye:{},labels:{}'.format(images.shape,images.dtype,labels)) print('images-len:' + str(len(images)) + ' labels-len: ' + str(len(labels))) for i in range(len(images)): show_image("image0", images[i, :, :, :]) a = np.zeros( (len(labels)) ) print(' a: ' +str(a)) for i in range(len(labels)): for j in range(len(labels[i])): if labels[i][j] > 0: a[i] = j print(' a: ' +str(a)) print('x: ' + str(x) + ' y_:' + str(y_)) images_x = np.reshape(images, (-1, 30000)) labels_y = np.reshape(labels, (-1, 6)) _,err,ac = sess.run([train_op,loss,acc],feed_dict={x:images, y_:labels_y}) # 50% 神经元在工作中 train_loss = train_loss + err train_acc = train_acc + ac print(" train loss: %f" % (np.sum(train_err)/n_batch)) print(" train acc: %f" % (np.sum(train_acc)/n_batch)) val_loss, val_acc = 0, 0 for i in range(val_batch): # test 在会话中取出images和labels测试数据, images_val2 主要是为了与 images_val 进行区分 images_val2, labels_val2 = sess.run([image_batch_val, label_batch_val]) val_loss, val_acc = sess.run([loss,acc], feed_dict={x:images_val_x, y_:labels_val2}) # 测试一下准确率,喂的数据是,图片和图片的标签 val_loss = val_loss + err val_acc = val_acc + ac print(" validation loss: %f" % (np.sum(val_loss)/val_batch)) print(" validation acc: %f" % (np.sum(val_acc)/val_batch)) # 停止所有线程 coord.request_stop() coord.join(threads) # 每个批次的大小 batch_size = 15 #每个批次 10,一次性放入100张图,放到神经网络中进行训练,以矩阵的形式放入 # 计算一共有多少个批次 # n_batch = mnist.train.num_examples // batch_size #整除 n_batch = get_example_nums(data_path) // batch_size val_batch = get_example_nums(data_path_val) // batch_size # 测试图片的数量 转换格式时以一个batch 放所有的图片 # val_num = get_example_nums(data_path_val) # 测试图片的数量 转换格式时以一个batch 放所有的图片 # train_num = get_example_nums(data_path) # 测试图片的数量 转换格式时以一个batch 放所有的图片 print ("-----------------" + str(n_batch) + " batch------------") #将所有的图片resize成100*100 w=100 h=100 c=3 #-----------------构建网络---------------------- #占位符 #-----------------构建网络---------------------- #占位符 x = tf.placeholder(tf.float32,[None,100,100,3],name='x-input') #图片像素 转换 一维向量,行与批次有关,none 代表行,列是784 y_=tf.placeholder(tf.float32,shape=[None,6],name='y_') def inference(input_tensor, train, regularizer): with tf.variable_scope('layer1-conv1'): conv1_weights = tf.get_variable("weight",[5,5,3,32],initializer=tf.truncated_normal_initializer(stddev=0.1)) conv1_biases = tf.get_variable("bias", [32], initializer=tf.constant_initializer(0.0)) conv1 = tf.nn.conv2d(input_tensor, conv1_weights, strides=[1, 1, 1, 1], padding='SAME') relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases)) with tf.name_scope("layer2-pool1"): pool1 = tf.nn.max_pool(relu1, ksize = [1,2,2,1],strides=[1,2,2,1],padding="VALID") with tf.variable_scope("layer3-conv2"): conv2_weights = tf.get_variable("weight",[5,5,32,64],initializer=tf.truncated_normal_initializer(stddev=0.1)) conv2_biases = tf.get_variable("bias", [64], initializer=tf.constant_initializer(0.0)) conv2 = tf.nn.conv2d(pool1, conv2_weights, strides=[1, 1, 1, 1], padding='SAME') relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases)) with tf.name_scope("layer4-pool2"): pool2 = tf.nn.max_pool(relu2, ksize=[1, 2 , 2, 1], strides=[1, 2, 2, 1], padding='VALID') with tf.variable_scope("layer5-conv3"): conv3_weights = tf.get_variable("weight",[3,3,64,128],initializer=tf.truncated_normal_initializer(stddev=0.1)) conv3_biases = tf.get_variable("bias", [128], initializer=tf.constant_initializer(0.0)) conv3 = tf.nn.conv2d(pool2, conv3_weights, strides=[1, 1, 1, 1], padding='SAME') relu3 = tf.nn.relu(tf.nn.bias_add(conv3, conv3_biases)) with tf.name_scope("layer6-pool3"): pool3 = tf.nn.max_pool(relu3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID') with tf.variable_scope("layer7-conv4"): conv4_weights = tf.get_variable("weight",[3,3,128,128],initializer=tf.truncated_normal_initializer(stddev=0.1)) conv4_biases = tf.get_variable("bias", [128], initializer=tf.constant_initializer(0.0)) conv4 = tf.nn.conv2d(pool3, conv4_weights, strides=[1, 1, 1, 1], padding='SAME') relu4 = tf.nn.relu(tf.nn.bias_add(conv4, conv4_biases)) with tf.name_scope("layer8-pool4"): pool4 = tf.nn.max_pool(relu4, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID') nodes = 6*6*128 reshaped = tf.reshape(pool4,[-1,nodes]) with tf.variable_scope('layer9-fc1'): fc1_weights = tf.get_variable("weight", [nodes, 1024], initializer=tf.truncated_normal_initializer(stddev=0.1)) if regularizer != None: tf.add_to_collection('losses', regularizer(fc1_weights)) fc1_biases = tf.get_variable("bias", [1024], initializer=tf.constant_initializer(0.1)) fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_weights) + fc1_biases) if train: fc1 = tf.nn.dropout(fc1, 0.5) with tf.variable_scope('layer10-fc2'): fc2_weights = tf.get_variable("weight", [1024, 512], initializer=tf.truncated_normal_initializer(stddev=0.1)) if regularizer != None: tf.add_to_collection('losses', regularizer(fc2_weights)) fc2_biases = tf.get_variable("bias", [512], initializer=tf.constant_initializer(0.1)) fc2 = tf.nn.relu(tf.matmul(fc1, fc2_weights) + fc2_biases) if train: fc2 = tf.nn.dropout(fc2, 0.5) with tf.variable_scope('layer11-fc3'): fc3_weights = tf.get_variable("weight", [512, 6], initializer=tf.truncated_normal_initializer(stddev=0.1)) if regularizer != None: tf.add_to_collection('losses', regularizer(fc3_weights)) fc3_biases = tf.get_variable("bias", [6], initializer=tf.constant_initializer(0.1)) logit = tf.matmul(fc2, fc3_weights) + fc3_biases return logit #---------------------------网络结束--------------------------- regularizer = tf.contrib.layers.l2_regularizer(0.0001) logits = inference(x,False,regularizer) #(小处理)将logits乘以1赋值给logits_eval,定义name,方便在后续调用模型时通过tensor名字调用输出tensor b = tf.constant(value=1,dtype=tf.float32) logits_eval = tf.multiply(logits,b,name='logits_eval') # loss=tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y_) loss = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=logits) train_op=tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss) correct_prediction = tf.equal(tf.cast(tf.argmax(logits,1),tf.float32), y_) acc= tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print("----------------------------") if __name__ == '__main__': range_num = 5 batch_test(data_path, 100, 100, n_batch, train_op, loss, acc, range_num, val_batch) ```
下了一个利用gym环境进行机器学习的代码,配置好环境后,运行失败,实在是看不懂了?
本人配置的环境是 tensorflow2.1.0 keras2.3.1 代码运行错误的输出如下 在网上找没找到出现类似问题的。。哭了 ``` Traceback (most recent call last): File ".\DeepQ_v0.py", line 157, in <module> learner.train() File ".\DeepQ_v0.py", line 110, in train update_target = np.copy(self.model.predict(old_state.reshape(1, self.input_width))[0]) File "D:\python3.6.3\lib\site-packages\keras\engine\training.py", line 1462, in predict callbacks=callbacks) File "D:\python3.6.3\lib\site-packages\keras\engine\training_arrays.py", line 324, in predict_loop batch_outs = f(ins_batch) File "D:\python3.6.3\lib\site-packages\tensorflow_core\python\keras\backend.py", line 3727, in __call__ outputs = self._graph_fn(*converted_inputs) File "D:\python3.6.3\lib\site-packages\tensorflow_core\python\eager\function.py", line 1551, in __call__ return self._call_impl(args, kwargs) File "D:\python3.6.3\lib\site-packages\tensorflow_core\python\eager\function.py", line 1591, in _call_impl return self._call_flat(args, self.captured_inputs, cancellation_manager) File "D:\python3.6.3\lib\site-packages\tensorflow_core\python\eager\function.py", line 1692, in _call_flat ctx, args, cancellation_manager=cancellation_manager)) File "D:\python3.6.3\lib\site-packages\tensorflow_core\python\eager\function.py", line 545, in call ctx=ctx) File "D:\python3.6.3\lib\site-packages\tensorflow_core\python\eager\execute.py", line 67, in quick_execute six.raise_from(core._status_to_exception(e.code, message), None) File "<string>", line 3, in raise_from tensorflow.python.framework.errors_impl.NotFoundError: '__inference_keras_scratch_graph_144' is neither a type of a primitive operation nor a name of a function registered in binary running on LAPTOP-JKA2BVQ. Make sure the operation or function is registered in the binary running in this process. ```
python3调用别人的opencv图片匹配程序报错
小白,调用别人python算法进行图片匹配报错。 代码: import cv2 from matplotlib import pyplot as plt import numpy as np import os import math def getMatchNum(matches,ratio): '''返回特征点匹配数量和匹配掩码''' matchesMask=[[0,0] for i in range(len(matches))] matchNum=0 for i,(m,n) in enumerate(matches): if m.distance<ratio*n.distance: #将距离比率小于ratio的匹配点删选出来 matchesMask[i]=[1,0] matchNum+=1 return (matchNum,matchesMask) path='D:/code/' queryPath=path+'yangben/' #图库路径 samplePath=path+'yuanjian/image1.jpg' #样本图片 comparisonImageList=[] #记录比较结果 #创建SIFT特征提取器 sift = cv2.xfeatures2d.SIFT_create() #创建FLANN匹配对象 FLANN_INDEX_KDTREE=0 indexParams=dict(algorithm=FLANN_INDEX_KDTREE,trees=5) searchParams=dict(checks=50) flann=cv2.FlannBasedMatcher(indexParams,searchParams) sampleImage=cv2.imread(samplePath,0) kp1, des1 = sift.detectAndCompute(sampleImage, None) #提取样本图片的特征 for parent,dirnames,filenames in os.walk(queryPath): for p in filenames: p=queryPath+p queryImage=cv2.imread(p,0) kp2, des2 = sift.detectAndCompute(queryImage, None) #提取比对图片的特征 matches=flann.knnMatch(des1,des2,k=2) #匹配特征点,为了删选匹配点,指定k为2,这样对样本图的每个特征点,返回两个匹配 (matchNum,matchesMask)=getMatchNum(matches,0.9) #通过比率条件,计算出匹配程度 matchRatio=matchNum*100/len(matches) drawParams=dict(matchColor=(0,255,0), singlePointColor=(255,0,0), matchesMask=matchesMask, flags=0) comparisonImage=cv2.drawMatchesKnn(sampleImage,kp1,queryImage,kp2,matches,None,**drawParams) comparisonImageList.append((comparisonImage,matchRatio)) #记录下结果 comparisonImageList.sort(key=lambda x:x[1],reverse=True) #按照匹配度排序 count=len(comparisonImageList) column=4 row=math.ceil(count/column) #绘图显示 figure,ax=plt.subplots(row,column) for index,(image,ratio) in enumerate(comparisonImageList): ax[int(index/column)][index%column].set_title('Similiarity %.2f%%' % ratio) ax[int(index/column)][index%column].imshow(image) plt.show() 报错信息: Traceback (most recent call last): File "sift7.py", line 55, in <module> ax[int(index/column)][index%column].set_title('Similiarity %.2f%%' % ratio) TypeError: 'AxesSubplot' object does not support indexing 求大神指点。
pip升级怎么提示这个 怎么 解决 老版本也删除了 我的是python 3.7
``` D:\python>python -m pip install --upgrade pip Collecting pip Downloading https://files.pythonhosted.org/packages/30/db/9e38760b32e3e7f40cce46dd5fb107b8c73840df38f0046d8e6514e675a1/pip-19.2.3-py2.py3-none-any.whl (1.4MB) 1% |▌ | 20kB 1.4kB/s eta 0:16:35Exception: Traceback (most recent call last): File "D:\python\lib\site-packages\pip\_vendor\urllib3\response.py", line 302, in _error_catcher yield File "D:\python\lib\site-packages\pip\_vendor\urllib3\response.py", line 384, in read data = self._fp.read(amt) File "D:\python\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 60, in read data = self.__fp.read(amt) File "D:\python\lib\http\client.py", line 447, in read n = self.readinto(b) File "D:\python\lib\http\client.py", line 491, in readinto n = self.fp.readinto(b) File "D:\python\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) File "D:\python\lib\ssl.py", line 1049, in recv_into return self.read(nbytes, buffer) File "D:\python\lib\ssl.py", line 908, in read return self._sslobj.read(len, buffer) socket.timeout: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\python\lib\site-packages\pip\_internal\basecommand.py", line 228, in main status = self.run(options, args) File "D:\python\lib\site-packages\pip\_internal\commands\install.py", line 291, in run resolver.resolve(requirement_set) File "D:\python\lib\site-packages\pip\_internal\resolve.py", line 103, in resolve self._resolve_one(requirement_set, req) File "D:\python\lib\site-packages\pip\_internal\resolve.py", line 257, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "D:\python\lib\site-packages\pip\_internal\resolve.py", line 210, in _get_abstract_dist_for self.require_hashes File "D:\python\lib\site-packages\pip\_internal\operations\prepare.py", line 310, in prepare_linked_requirement progress_bar=self.progress_bar File "D:\python\lib\site-packages\pip\_internal\download.py", line 837, in unpack_url progress_bar=progress_bar File "D:\python\lib\site-packages\pip\_internal\download.py", line 674, in unpack_http_url progress_bar) File "D:\python\lib\site-packages\pip\_internal\download.py", line 898, in _download_http_url _download_url(resp, link, content_file, hashes, progress_bar) File "D:\python\lib\site-packages\pip\_internal\download.py", line 618, in _download_url hashes.check_against_chunks(downloaded_chunks) File "D:\python\lib\site-packages\pip\_internal\utils\hashes.py", line 48, in check_against_chunks for chunk in chunks: File "D:\python\lib\site-packages\pip\_internal\download.py", line 586, in written_chunks for chunk in chunks: File "D:\python\lib\site-packages\pip\_internal\utils\ui.py", line 159, in iter for x in it: File "D:\python\lib\site-packages\pip\_internal\download.py", line 575, in resp_read decode_content=False): File "D:\python\lib\site-packages\pip\_vendor\urllib3\response.py", line 436, in stream data = self.read(amt=amt, decode_content=decode_content) File "D:\python\lib\site-packages\pip\_vendor\urllib3\response.py", line 401, in read raise IncompleteRead(self._fp_bytes_read, self.length_remaining) File "D:\python\lib\contextlib.py", line 130, in __exit__ self.gen.throw(type, value, traceback) File "D:\python\lib\site-packages\pip\_vendor\urllib3\response.py", line 307, in _error_catcher raise ReadTimeoutError(self._pool, None, 'Read timed out.') pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out. ```
python 关于对象实例化的问题
``` class Node(object): # self 当我们实例化一个对象的情况下,再去调用这个函数的时候,这个实例就是self def __init__(self, data, next = None): self.data = data self.next = next class Stack(object): #用到的模块更多 def __init__(self, top = None): # none 就是一个对象 self.top = top def push(self,data): #创建新的节点放到栈顶 self.top = Node(data, self.top) def pop(self): #拿出栈顶元素,原来的栈发生改变 if self.top is None: return None data = self.top.data self.top = self.top.next return data def peek(self): #查看栈顶元素,原来的栈不变 return self.top.data if self.top is not None else None def isEmpty(self): return self.peek() is None if __name__ == "__main__": #别的模块调用这个模块下程序的入口 stack = Stack() stack1 = stack.push(1) stack1 = stack.push(2) print stack.peek(), #查看栈顶元素 stack.pop() print stack.peek() #输出: 2 1 ``` 这个是python stack()的源代码,这里面出现了top,data,但是并没有声明对象的类型? Python中不声明对象类型,是可以用任何类型吗还是什么意思?
python递归 return 问题
``` class Solution: def canJump(self, nums): if len(nums) == 0: return False def DFS(nums): if len(nums) == 1: return True for i in range(1,nums[0]+1): return DFS(nums[i:]) #上面这两行代码如果改成 return DFS(nums[1:]、 DFS(nums[2:]......)则可以运行,但是引入for循环后,return就变为None) S =Solution() S.canJump([2,0,0]) ``` 想知道怎么解决?卡了我好久
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私有的数
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
此博客仅为我业余记录文章所用,发布到此,仅供网友阅读参考,如有侵权,请通知我,我会删掉。 补充 有不少读者留言说本文章没有用,因为天气预报直接打开手机就可以收到了,为何要多此一举发送到邮箱呢!!!那我在这里只能说:因为你没用,所以你没用!!! 这里主要介绍的是思路,不是天气预报!不是天气预报!!不是天气预报!!!天气预报只是用于举例。请各位不要再刚了!!! 下面是我会用到的两个场景: 每日下
Python 植物大战僵尸代码实现(2):植物卡片选择和种植
这篇文章要介绍的是: - 上方植物卡片栏的实现。 - 点击植物卡片,鼠标切换为植物图片。 - 鼠标移动时,判断当前在哪个方格中,并显示半透明的植物作为提示。
死磕YOLO系列,YOLOv1 的大脑、躯干和手脚
YOLO 是我非常喜欢的目标检测算法,堪称工业级的目标检测,能够达到实时的要求,它帮我解决了许多实际问题。 这就是 YOLO 的目标检测效果。它定位了图像中物体的位置,当然,也能预测物体的类别。 之前我有写博文介绍过它,但是每次重新读它的论文,我都有新的收获,为此我准备写一个系列的文章来详尽分析它。这是第一篇,从它的起始 YOLOv1 讲起。 YOLOv1 的论文地址:https://www.c
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的 回答 - Bravo Yeung,获得该问题下回答中得最高赞(236赞和1枚专业勋章),对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalk
记一次腾讯面试:进程之间究竟有哪些通信方式?如何通信? ---- 告别死记硬背
有一次面试的时候,被问到进程之间有哪些通信方式,不过由于之前没深入思考且整理过,说的并不好。想必大家也都知道进程有哪些通信方式,可是我猜很多人都是靠着”背“来记忆的,所以今天的这篇文章,讲给大家详细着讲解他们是如何通信的,让大家尽量能够理解他们之间的区别、优缺点等,这样的话,以后面试官让你举例子,你也能够顺手拈来。 1、管道 我们来看一条 Linux 的语句 netstat -tulnp | gr...
20行Python代码爬取王者荣耀全英雄皮肤
引言 王者荣耀大家都玩过吧,没玩过的也应该听说过,作为时下最火的手机MOBA游戏,咳咳,好像跑题了。我们今天的重点是爬取王者荣耀所有英雄的所有皮肤,而且仅仅使用20行Python代码即可完成。 准备工作 爬取皮肤本身并不难,难点在于分析,我们首先得得到皮肤图片的url地址,话不多说,我们马上来到王者荣耀的官网: 我们点击英雄资料,然后随意地选择一位英雄,接着F12打开调试台,找到英雄原皮肤的图片
网络(8)-HTTP、Socket、TCP、UDP的区别和联系
TCP/IP协议是传输层协议,主要解决数据如何在网络中传输,而HTTP是应用层协议,主要解决如何包装数据。 一、TCP与UDP的不同 1. 是否需要建立连接。 UDP在传送数据之前不需要先建立连接;TCP则提供面向连接的服务; 2. 是否需要给出确认 对方的传输层在收到UDP报文后,不需要给出任何确认,而 TCP需要给出确认报文,要提供可靠的、面向连接的传输服务。 3.虽然UDP不提供可靠交...
简明易理解的@SpringBootApplication注解源码解析(包含面试提问)
欢迎关注文章系列 ,关注我 《提升能力,涨薪可待》 《面试知识,工作可待》 《实战演练,拒绝996》 欢迎关注我博客,原创技术文章第一时间推出 也欢迎关注公 众 号【Ccww笔记】,同时推出 如果此文对你有帮助、喜欢的话,那就点个赞呗,点个关注呗! 《提升能力,涨薪可待篇》- @SpringBootApplication注解源码解析 一、@SpringBootApplication 的作用是什
防劝退!数据结构和算法难理解?可视化动画带你轻松透彻理解!
大家好,我是 Rocky0429,一个连数据结构和算法都不会的蒟蒻… 学过数据结构和算法的都知道这玩意儿不好学,没学过的经常听到这样的说法还没学就觉得难,其实难吗?真难! 难在哪呢?当年我还是个小蒟蒻,初学数据结构和算法的时候,在忍着枯燥看完定义原理,之后想实现的时候,觉得它们的过程真的是七拐八绕,及其难受。 在简单的链表、栈和队列这些我还能靠着在草稿上写写画画理解过程,但是到了数论、图...
西游记团队中如果需要裁掉一个人,会先裁掉谁?
2019年互联网寒冬,大批企业开始裁员,下图是网上流传的一张截图: 裁员不可避免,那如何才能做到不管大环境如何变化,自身不受影响呢? 我们先来看一个有意思的故事,如果西游记取经团队需要裁员一名,会裁掉谁呢,为什么? 西游记团队组成: 1.唐僧 作为团队teamleader,有很坚韧的品性和极高的原则性,不达目的不罢休,遇到任何问题,都没有退缩过,又很得上司支持和赏识(直接得到唐太宗的任命,既给
开挂的人生!那些当选院士,又是ACM/IEEE 双料Fellow的华人学者们
昨日,2019年两院院士正式官宣,一时间抢占了各大媒体头条。 朋友圈也是一片沸腾,奔走相告,赶脚比自己中了大奖还嗨皮! 谁叫咱家导师就是这么厉害呢!!! 而就在最近,新一年度的IEEE/ACM Fellow也将正式公布。 作为学术届的顶级荣誉,不自然地就会将院士与Fellow作比较,到底哪个含金量更高呢? 学术君认为,同样是专业机构对学者的认可,考量标准不一,自然不能一概而论。 但...
聊聊C语言和指针的本质
坐着绿皮车上海到杭州,24块钱,很宽敞,在火车上非正式地聊几句。 很多编程语言都以 “没有指针” 作为自己的优势来宣传,然而,对于C语言,指针却是与生俱来的。 那么,什么是指针,为什么大家都想避开指针。 很简单, 指针就是地址,当一个地址作为一个变量存在时,它就被叫做指针,该变量的类型,自然就是指针类型。 指针的作用就是,给出一个指针,取出该指针指向地址处的值。为了理解本质,我们从计算机模型说起...
Python语言高频重点汇总
Python语言高频重点汇总 GitHub面试宝典仓库——点这里跳转 文章目录Python语言高频重点汇总**GitHub面试宝典仓库——点这里跳转**1. 函数-传参2. 元类3. @staticmethod和@classmethod两个装饰器4. 类属性和实例属性5. Python的自省6. 列表、集合、字典推导式7. Python中单下划线和双下划线8. 格式化字符串中的%和format9.
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观
代码详解:如何用Python快速制作美观、炫酷且有深度的图表
全文共12231字,预计学习时长35分钟生活阶梯(幸福指数)与人均GDP(金钱)正相关的正则图本文将探讨三种用Python可视化数据的不同方法。以可视化《2019年世界幸福报告》的数据为例,本文用Gapminder和Wikipedia的信息丰富了《世界幸福报告》数据,以探索新的数据关系和可视化方法。《世界幸福报告》试图回答世界范围内影响幸福的因素。报告根据对“坎特里尔阶梯问题”的回答来确定幸...
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外
(经验分享)作为一名普通本科计算机专业学生,我大学四年到底走了多少弯路
今年正式步入了大四,离毕业也只剩半年多的时间,回想一下大学四年,感觉自己走了不少弯路,今天就来分享一下自己大学的学习经历,也希望其他人能不要走我走错的路。 (一)初进校园 刚进入大学的时候自己完全就相信了高中老师的话:“进入大学你们就轻松了”。因此在大一的时候自己学习的激情早就被抛地一干二净,每天不是在寝室里玩游戏就是出门游玩,不过好在自己大学时买的第一台笔记本性能并不是很好,也没让我彻底沉...
如何写一篇技术博客,谈谈我的看法
前言 只有光头才能变强。 文本已收录至我的GitHub精选文章,欢迎Star:https://github.com/ZhongFuCheng3y/3y 我一直推崇学技术可以写技术博客去沉淀自己的知识,因为知识点实在是太多太多了,通过自己的博客可以帮助自己快速回顾自己学过的东西。 我最开始的时候也是只记笔记,认为自己能看得懂就好。但如果想验证自己是不是懂了,可以写成技术博客。在写技术博客的...
字节跳动面试官这样问消息队列:分布式事务、重复消费、顺序消费,我整理了一下
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式和人才交流群,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸...
面试还搞不懂redis,快看看这40道面试题(含答案和思维导图)
Redis 面试题 1、什么是 Redis?. 2、Redis 的数据类型? 3、使用 Redis 有哪些好处? 4、Redis 相比 Memcached 有哪些优势? 5、Memcache 与 Redis 的区别都有哪些? 6、Redis 是单进程单线程的? 7、一个字符串类型的值能存储最大容量是多少? 8、Redis 的持久化机制是什么?各自的优缺点? 9、Redis 常见性...
大学四年自学走来,这些珍藏的「实用工具/学习网站」我全贡献出来了
知乎高赞:文中列举了互联网一线大厂程序员都在用的工具集合,涉及面非常广,小白和老手都可以进来看看,或许有新收获。
互联网公司的裁员,能玩出多少种花样?
裁员,也是一门学问,可谓博大精深!以下,是互联网公司的裁员的多种方法:-正文开始-135岁+不予续签的理由:千禧一代网感更强。95后不予通过试用期的理由:已婚已育员工更有责任心。2通知接下来要过苦日子,让一部分不肯同甘共苦的员工自己走人,以“兄弟”和“非兄弟”来区别员工。3强制996。员工如果平衡不了工作和家庭,可在离婚或离职里二选一。4不布置任何工作,但下班前必须提交千字工作日报。5不给活干+...
【设计模式】单例模式的八种写法分析
网上泛滥流传单例模式的写法种类,有说7种的,也有说6种的,当然也不排除说5种的,他们说的有错吗?其实没有对与错,刨根问底,写法终究是写法,其本质精髓大体一致!因此完全没必要去追究写法的多少,有这个时间还不如跟着宜春去网吧偷耳机、去田里抓青蛙得了,一天天的....
《面试宝典》:检验是否为合格的初中级程序员的面试知识点,你都知道了吗?查漏补缺
欢迎关注文章系列,一起学习 《提升能力,涨薪可待篇》 《面试知识,工作可待篇》 《实战演练,拒绝996篇》 也欢迎关注公 众 号【Ccww笔记】,原创技术文章第一时间推出 如果此文对你有帮助、喜欢的话,那就点个赞呗,点个关注呗! 《面试知识,工作可待篇》-Java笔试面试基础知识大全 前言 是不是感觉找工作面试是那么难呢? 在找工作面试应在学习的基础进行总结面试知识点,工作也指日可待,欢...
关于研发效能提升的思考
研发效能提升是最近比较热门的一个话题,本人根据这几年的工作心得,做了一些思考总结,由于个人深度有限,暂且抛转引入。 三要素 任何生产力的提升都离不开这三个因素:人、流程和工具,少了其中任何一个因素都无法实现。 人,即思想,也就是古人说的“道”,道不同不相为谋,是制高点,也是高层建筑的基石。 流程,即方法,也是古人说的“法”。研发效能的提升,也就是要提高投入产出比,既要增加产出,也要减...
微博推荐算法简述
在介绍微博推荐算法之前,我们先聊一聊推荐系统和推荐算法。有这样一些问题:推荐系统适用哪些场景?用来解决什么问题、具有怎样的价值?效果如何衡量? 推荐系统诞生很早,但真正被大家所重视,缘起于以”facebook”为代表的社会化网络的兴起和以“淘宝“为代表的电商的繁荣,”选择“的时代已经来临,信息和物品的极大丰富,让用户如浩瀚宇宙中的小点,无所适从。推荐系统迎来爆发的机会,变得离用户更近: 快...
相关热词 c#判断数字不得为负数 c#帧和帧协议 c#算偏移值 c# 在枚举中 c#6 字符串 插值 c#程序中的占位符标签 c#监听数组变化 c# vlc c#索引实现 c# 局域网广播通信
立即提问