简体   繁体   English

如何将一些整数替换为字符串?

[英]How can I replace some integers to strings?

I started to learning today Python.我今天开始学习Python。 I am trying to make a Fate dice bot for Discord.我正在尝试为 Discord 制作一个 Fate 骰子机器人。 I want to replace an integer with a string and I wrote:我想用一个字符串替换一个整数,我写道:

zarList = [1,-1,0]

zarsonuc = random.choices(zarList, k=4)

zarsonucsayi = sum(zarsonuc)

zartanim = {-4:'Felaket', -3:'Rezalet', -2:'Kötü', -1:'Dandik', 0:'Düz', 1:'Eh', 2:'İyi', 3:'Baya İyi', 4:'Harika'}
tanimsonuc = [zartanim.get(n,n) for n in zarsonucsayi]

await ctx.send(f"{tanimsonuc} bir zar attın.{sonuc},{zarsonucsayi}")`

But I take this TypeError :(但我接受这个 TypeError :(

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not iterable. discord.ext.commands.errors.CommandInvokeError:命令引发异常:TypeError:“int”对象不可迭代。

Can anyone help me?谁能帮我?

If you want to replace an integer to a string you can just cast it to a string.如果要将整数替换为字符串,只需将其转换为字符串即可。 For example, if you want to cast the first number of your array to a string you may say:例如,如果您想将数组的第一个数字转换为字符串,您可以说:

str(zarList[0])

Hope it helps,(just answered by what you asked on the title)希望它有所帮助,(只是通过您在标题中提出的问题来回答)

Upon looking at your code, the error doesn't appear because the list elements are not a string but because you are trying to iterate over an int element and not an iterable object.在查看您的代码时,不会出现错误因为列表元素不是字符串,而是因为您试图迭代int元素而不是可迭代对象。 Here:这里:

tanimsonuc = [tanim.get(n,n) for n in zarsonucsayi]

Since自从

zarsonucsayi = sum(zarsonuc)

returns an int value, and you can't iterate it.返回一个int值,你不能迭代它。

zarList = [str(x) for x in zarList]

基本上你遍历列表并使用 str 将其转换为字符串

You need to iterate using the range您需要使用range进行迭代

tanimsonuc = [zartanim[n] for n in range(zar_sonuc_sayi)]

Output:输出:

['Düz', 'Eh', 'İyi', 'Baya İyi']

Explanation解释


  • [zartanim.get(n,n) for n in zarsonucsayi]

    You need to iterate through zarsonucsayi to do that use range(zarsonucsayi)您需要遍历zarsonucsayi才能使用range(zarsonucsayi)

    You wanted the value of the corresponding dice value, use zartanim[n]您想要相应骰子值的值,请使用zartanim[n]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM