str_x = 'int_value=233/str_value=hello' dict_x = dict(element.split('=') for element in str_x.split('/')) print(dict_x) print(int(dict_x['int_value'])) print(dict_x['str_value'])
这段代码可以正常运行,但是为什么放到 pycharm 里爆黄呢,请问怎么改才能不爆黄呢?
dict()里边爆黄:
Unexpected type(s): (Generator[List[str], Any, None]) Possible type(s): (SupportsKeysAndGetItem[List[str], _VT]) (Iterable[Tuple[Any, Any]])
![]() | 1 aladdinding 2022-11-16 11:53:16 +08:00 dict_x = dict(tuple(element.split('=')) for element in str_x.split('/')) |
![]() | 2 fenglala OP @aladdinding 还是爆黄,爆黄信息变了 Unexpected type(s): (Generator[Tuple[str, ...], Any, None]) Possible type(s): (SupportsKeysAndGetItem[Tuple[str, ...], _VT]) (Iterable[Tuple[Any, Any]]) |
![]() | 3 westoy 2022-11-16 11:59:11 +08:00 dict(element.split('=', 1) for element in str_x.split('/')) 不过不建议直接搞, 去看看 pyparsing 之类的 |
4 aloxaf 2022-11-16 12:01:20 +08:00 element.split('=') 可能产生有长度超过 2 的 list ,理论上加上 maxsplit=1 就能满足要求,可惜 pycharm 还没有这么高级 你只能选择这样干,嫌太长可以用海象运算符简化 dict_x = dict((element.split('=')[0], element.split('=')[1]) for element in str_x.split('/')) 当然我更建议 # noinspection PyTypeChecker dict_x = dict(element.split('=') for element in str_x.split('/')) |
![]() | 5 fenglala OP @westoy 也爆黄,提示信息变成: Unexpected type(s): (Generator[List[str], Any, None]) Possible type(s): (SupportsKeysAndGetItem[List[str], _VT]) (Iterable[Tuple[Any, Any]]) |
![]() | 7 fenglala OP @aloxaf 按照你的思路,这样写也不爆黄了,不用 split 两遍 dict_x = dict((element.split('=')[0:2]) for element in str_x.split('/')) |
![]() | 8 hellojay 2022-11-16 12:04:53 +08:00 dict_x = {element.split('=')[0]: element.split('=')[1] for element in str_x.split('/')} |
![]() | 9 fenglala OP 啊不行,我大意了,是我前边有 noinspection PyTypeChecker 导致的,我 7 楼的回复还是爆黄 |
![]() | 10 fenglala OP dict_x = dict((kv[0], kv[1]) for kv in (element.split('=') for element in str_x.split('/'))) 这个可以了!不用多一次 split ! |
![]() | 11 hellojay 2022-11-16 12:16:06 +08:00 @fenglala #10 这个让代码没有任何可读性,你少了一个 split 却多了一个 for dict_x = {element.split('=')[0]: element.split('=')[1] for element in str_x.split('/')} 这个也不爆黄 |
![]() | 12 xuboying 2022-11-16 13:13:43 +08:00 ![]() 能不能说文雅一点的告警或者出错。 爆黄,在一众标题里显得很黄很暴力。。。 |
![]() | 13 hsfzxjy 2022-11-16 13:47:24 +08:00 via Android 不要太在意这个,告警是静态检查器蠢,不是你写的有问题 |
![]() | 14 luckyx 2022-11-16 13:58:01 +08:00 text = 'int_value=233/str_value=hello' print({k: v for k,v in [e.split('=') for e in text.split('/')]}) Leetcode playground 能过 |
![]() | 15 yernsun 2022-11-16 16:05:08 +08:00 ![]() import urllib.parse dict(urllib.parse.parse_qsl('int_value=233/str_value=hello', separator='/')) |
16 zhanglintc 2022-11-17 00:16:10 +08:00 @xuboying #12 其实应该是“报黄”,哈哈。 |
![]() | 17 llsquaer 2022-11-17 09:26:37 +08:00 怎么就那么喜欢一行写代码... {key:value for key,value in map(lambda item:item.split('='),str_x.split('/'))} |
![]() | 18 u823tg 2022-11-17 11:53:26 +08:00 ![]() 是 pycharm 的问题吧, 建议别用-_-。 |