Python - 不支持的类型:范围和范围

2023-11-08Python开发问题
2

本文介绍了Python - 不支持的类型:范围和范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在尝试运行脚本时遇到了这个奇怪的错误,代码似乎是正确的,但似乎 python (3) 不喜欢这部分:

I'm getting this strange error trying to run a script, the code appears to be correct but it seems python (3) didn't liked this part:

        def function(x):
                  if integer:
                    return int(x)
                else:
                    return x

            non_nil = randrange(21)
            d = dict([(randrange(101), Racional(coeff(randrange(-20,20)),
                                    coeff(choice(range(-30,0)+
                                                 range(1,30)))))
                     for k in range(non_nil)])

我收到以下错误:

for k in range(non_nil)]) unsupported operand type(s) for +: 'range' and 'range'

我已经尝试将最后四行放在一个单独的行中,但 python 返回相同的错误.

I already tried to put the last four lines in a single one but python returns the same error.

推荐答案

这是因为 Python 3 range 不像 Python 2 那样返回 list.这段代码是为 Python 2 编写.

This is because Python 3 range does not return a list, unlike Python 2. This code was written for Python 2.

此代码应该更改:

range(-30,0) + range(1,30)

应该改为:

[*range(-30,0), *range(1,30)]

在 Python 3.5 之前(2015 年,PEP 448 - 附加解包概括),你不能在列表中使用 *,必须这样写(或者你可能更喜欢这样):

Prior to Python 3.5 (2015, PEP 448 - Additional Unpacking Generalizations), you cannot use * inside lists, and must write it this way instead (or you may prefer this):

list(range(-30,0)) + list(range(1,30))

这篇关于Python - 不支持的类型:范围和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10