我有一个元组列表:
data = [('Team1', 'Mark Owen', 40),
('Team1', 'John Doe', 25),
('Team2', 'Raj Patel', 40),
('Team3', 'Matt Le Blanc', 30),
('Team1', 'Rene Russo', 40),
('Team1', 'Ronald Regan', 40),
('Team3', 'Dean Saunders', 15),
('Team2', 'Michael Antonio', 30)]
Run Code Online (Sandbox Code Playgroud)
我想分组(每个元组的索引[0]),计算每个团队中的数字或人数(索引[1])并总结与每个团队相关的数字(索引[2])但我无法想象这个出.到目前为止,我已经尝试使用defaultdict(list)返回一个dict,例如我试过这个按团队分组:
def create_hrs_totals():
result = defaultdict(list)
for k, *v in data():
result[k] += v
return dict(result)
Run Code Online (Sandbox Code Playgroud)
但后来我正在努力使用输出来实现我需要使用列表comp或其他...我正在寻找的结果是一个新的列表:
[Team1, 4, 145,
Team2, 2, 80,
Team3, 2, 70]
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?
嗨,我试图让我的不和谐机器人做我在我的不和谐客户端中输入的内容,我想使用 exec() + 这只是为了测试和实验,所以它是否不安全并不重要。
我的代码的一部分:
import discord
client = discord.Client()
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('2B: '):
exec(message.content[4:]) # <--- here is the exec()
.
.
.
Run Code Online (Sandbox Code Playgroud)
但这是我输入时的错误,
2B: await client.send_message(message.channel, 'please stay quiet -.-')
Run Code Online (Sandbox Code Playgroud)
错误:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Shiyon\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:\Users\Shiyon\Desktop\dm_1.py", line 12, in on_message
exec(message.content[4:])
File "<string>", line 1
await client.send_message(message.channel, 'please stay quiet -.-')
^
SyntaxError: …
Run Code Online (Sandbox Code Playgroud) 我的班级在连接到服务器时应立即发送登录字符串,然后在会话结束后应发送退出字符串并清理套接字。下面是我的代码。
import trio
class test:
_buffer = 8192
_max_retry = 4
def __init__(self, host='127.0.0.1', port=12345, usr='user', pwd='secret'):
self.host = str(host)
self.port = int(port)
self.usr = str(usr)
self.pwd = str(pwd)
self._nl = b'\r\n'
self._attempt = 0
self._queue = trio.Queue(30)
self._connected = trio.Event()
self._end_session = trio.Event()
@property
def connected(self):
return self._connected.is_set()
async def _sender(self, client_stream, nursery):
print('## sender: started!')
q = self._queue
while True:
cmd = await q.get()
print('## sending to the server:\n{!r}\n'.format(cmd))
if self._end_session.is_set():
nursery.cancel_scope.shield = True …
Run Code Online (Sandbox Code Playgroud) 我在使用sorted()
方法时遇到问题。我在循环中使用此方法对我在循环的每个步骤中升级的列表进行排序。第一次迭代有效,但第二次超越没有,并给我下一个错误:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import numpy as np
import random as rd
import math
Poblacion = 10
pressure = int(0.3*Poblacion)
mutation_chance = 0.08
Modelo = np.array([[0.60,0.40,0.90],[0.26,0.20,0.02],[0.80,0.00,0.05]])
x = np.array([[1.0,2.0,3.0],[0.70,0.50,0.90],[0.10,0.40,0.20]])
y = np.array([[4.10,0.72,2.30],[1.43,0.30,1.01],[0.40,0.11,0.18]])
def crearIndividuo():
return[np.random.random((3, 3))]
def crearPoblacion():
return [crearIndividuo() for i in range(Poblacion)]
def calcularFitness(individual):
error = 0
i=0
for j in x:
error += np.array(individual).dot(j)-y[i]
i += 1
error = …
Run Code Online (Sandbox Code Playgroud) 我试图让我的 !say 命令只对机器人所有者有效。这是我目前拥有的
@bot.command(pass_context = True)
async def say(ctx, *args):
mesg = ' '.join(args)
await bot.delete_message(ctx.message)
return await bot.say(mesg)
Run Code Online (Sandbox Code Playgroud)
该代码有效,但我想让它只有我(机器人所有者)才能运行该命令。
首先,道歉。我对 Python 还很陌生。我有 Java/C# 编码背景。我在很多方面都喜欢 Python 的简单性,但也发现一些标准很难确定。
例如,我已经成功地运行了一个 Discord 机器人。异步方法运行良好。但我想安排一个作业每(比如)30 分钟运行一次。然而,当我输入 asyncio.run(job()) 时,Python 告诉我“run”不是 asyncio 的属性。我真的不知道为什么会这么说。哎呀,asyncio 是做到这一点的“正确”方法吗?
有没有可能不和谐的导入以某种方式掩盖了它?我想我可能需要买本书什么的!
再次感谢。我确实尝试对此进行搜索,但没有任何结果!
我想在触发时删除一条单一消息,但我无法弄清楚。我正在使用 purge,await ctx.channel.purge
但这不是我想要的,因为这需要一定的量
旧版本是这样写的,await self.bot.delete_message(ctx.message)
但现在会带来错误object has no attribute 'bot'
阅读文档我能找到的只是Message.delete
但这带来了错误:NameError: name 'Message' is not defined
我确信这是一个简单的解决方案,但我无法解决。提前致谢
我当前的代码是:
@commands.command(pass_context=True)
async def say(self, ctx, *args):
'''Make Bot repeat your messages'''
mesg = ' '.join(args)
await Message.delete(ctx.message)
await ctx.send(mesg)`
Run Code Online (Sandbox Code Playgroud) 在我的不和谐机器人中,我有 2 个命令可以提供和创建角色。它们工作得很好,但如果角色名称包含空格,我就会遇到问题。它将第二个单词计入第二个参数,使命令产生错误。
# Giverole
@client.command(name='giverole',
aliases=['gr'],
brief='Assgins role to a user',
pass_ctx=True)
async def giverole(ctx, rname, *, member: discord.Member):
role = get(member.guild.roles, name=rname)
await member.add_roles(role)
await ctx.send(f'Role added to user {member.mention}')
print('Giverole command executed\n- - -')
# Createrole
@client.command(name='createrole',
brief='Creates a role',
aliases=['cr','makerole'],
pass_ctx=True)
async def createrole(ctx, rname: str, clr: discord.Colour):
if ctx.author.guild_permissions.manage_roles:
await ctx.guild.create_role(name=rname, colour=clr)
await ctx.send('Role created with name: ' + rname)
print('Createrole command executed\n- - -')
else:
await ctx.send('You lack permission.')
print('Createrole command executed\n- - -') …
Run Code Online (Sandbox Code Playgroud) 我正在用Python(3.7.3)制作一个Discord Bot,我想向用户发送一条带有服务器邀请链接的DM。这是我的代码:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=config.get_config, description='Thou Holy Bot')
@bot.command(name='dm',pass_context=True)
async def dm(ctx, *, argument):
<code here>
Run Code Online (Sandbox Code Playgroud)
我有一个discord.member.Member() 类。我想创建一个到频道的邀请链接(如果需要的话,有一个频道对象)并将其发送给用户。任何帮助表示赞赏,谢谢!
我正在用 Python 编写一个用于discord 的机器人。我希望当有人登录到服务器时,他被赋予一定的角色
\n\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import bot\nbot = commands.Bot(command_prefix=\'!\')\nfrom discord.utils import get\n\n@bot.event\nasync def on_member_join(member):\n role = get(member.roles, name="\xd0\x98\xd0\xb3\xd1\x80\xd0\xbe\xd0\xba\xd0\xb8")\n await bot.add_roles(member, role)\n
Run Code Online (Sandbox Code Playgroud)\n\n当我启动并且有人进入服务器时,出现以下错误:\nAttributeError: \'Bot\' object has no attribute \'add_roles\'
\npython ×9
discord.py ×7
discord ×5
python-3.x ×4
numpy ×1
python-3.5 ×1
python-3.6 ×1
python-trio ×1
sorting ×1