我在Python工作,我有一个整数列表:[1, 2, 1, 3, 2, 2, 1, 3].
我想为每个整数分配一个字符串,好像它是一个变量:
['red', 'orange', 'red', 'yellow', 'orange', 'orange', 'red', 'yellow'].
我该怎么做呢?
在该示例中,1对应于'red',2对应于'orange'并3对应于'yellow'.
谢谢!
基本上我只需要弄清楚如何从Python的列表中生成模式(最常出现的数字),无论该列表是否有多种模式?
像这样的东西:
def print_mode (thelist):
counts = {}
for item in thelist:
counts [item] = counts.get (item, 0) + 1
maxcount = 0
maxitem = None
for k, v in counts.items ():
if v > maxcount:
maxitem = k
maxcount = v
if maxcount == 1:
print "All values only appear once"
if counts.values().count (maxcount) > 1:
print "List has multiple modes"
else:
print "Mode of list:", maxitem
Run Code Online (Sandbox Code Playgroud)
但是,不是在"所有值只显示一次"或"列表有多种模式"中返回字符串,我希望它返回它引用的实际整数?
我正在尝试使用PHP来创建文本文件,但我不断收到"无法打开文件"错误.谁能告诉我我做错了什么?
chmod('text.txt', 0777);
$textFile = "text.txt";
$fileHandle = fopen($textFile, 'w') or die("can't open file");
$stringData = "Hello!";
fwrite($fileHandle, $stringData);
fclose($fileHandle);
Run Code Online (Sandbox Code Playgroud)