TypeError:“范围"对象不支持项目分配

2024-04-20Python开发问题
5

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

问题描述

我正在查看一些 python 2.x 代码并试图将其转换为 py 3.x 但我被困在这一部分.谁能澄清什么是错的?

I was looking at some python 2.x code and attempted to translate it to py 3.x but I'm stuck on this section. Could anyone clarify what is wrong?

import random

emails = {
    "x": "[REDACTED]@hotmail.com",
    "x2": "[REDACTED]@hotmail.com",
    "x3": "[REDACTED]@hotmail.com"
}

people = emails.keys()

#generate a number for everyone
allocations = range(len(people))
random.shuffle(allocations)

这是给出的错误:

TypeError: 'range' object does not support item assignment

推荐答案

在 Python 3 中,range 返回一个惰性序列对象——它不返回一个列表.无法重新排列范围对象中的元素,因此无法对其进行混洗.

In Python 3, range returns a lazy sequence object - it does not return a list. There is no way to rearrange elements in a range object, so it cannot be shuffled.

在洗牌之前将其转换为列表.

Convert it to a list before shuffling.

allocations = list(range(len(people)))

这篇关于TypeError:“范围"对象不支持项目分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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