初学者。Python列表。整型字符串(&s)

2024-04-20 11:00:23 发布

您现在位置:Python中文网/ 问答频道 /正文

def changeList(myList):
    myList = myList[3:]
    new_list = []

    count = -1
    for line in myList:
        count += 1
        new_list += [list(myList[count])]

    count1 = -1
    for i in new_list:

         count1 += 1
         count2 = -1

         for j in i:

             count2 += 1

             if j == "-":
                 new_list[count1][count2] = 0 #- 0 - Can't go there.
             elif j == "|":
                 new_list[count1][count2] = 0 #| 0 - Can't go there.
             elif j == "+":
                 new_list[count1][count2] = 0 #+ 0 - Can't go there.
             elif j == " ":
                 new_list[count1][count2] = 1 #Blank - 1 for empty cell.

    for i in new_list:

       print(i)

    return new_list

为什么我这么做。。。你知道吗

print(type(new_list[0][0]))

它以字符串形式返回类型?我需要它是一个int,就像我指定的那样。当我打印出新的目录时。它不会将内容显示为[“0”,“0”,…等]而是将它们显示为[0,0,0…等]它们必须是整数。我错过了什么。谢谢。你知道吗

我在函数(myList)中输入的参数如下所示。。。你知道吗

['10 20', '1 1', '10 20', '-----------------------------------------', '|     |       | | |       |     | |     |', '|-+ +-+-+ + + + + + +-+ + + +-+-+ + + +-|'...etc

我想去

new_list[0][0] = 3

但它不会让我!?你知道吗


Tags: ingonewfordefcountcanlist
1条回答
网友
1楼 · 发布于 2024-04-20 11:00:23

myList,您的输入有字符串值。你知道吗

myList = ['|     |       | | |       |     | |     |', '|-+ +-+-+ + + + + + +-+ + + +-+-+ + + +-|']

将列表转换为二维列表。你知道吗

new_list = [list(i) for i in myList]

现在我们循环将字符串值更改为整数。你知道吗

count1 = -1
for i in new_list:
    count1 += 1
    count2 = -1

    for j in i:

        count2 += 1
        if j == "-":
            new_list[count1][count2] = 0 #- 0 - Can't go there.
        elif j == "|":
            new_list[count1][count2] = 0 #| 0 - Can't go there.
        elif j == "+":
            new_list[count1][count2] = 0 #+ 0 - Can't go there.
        elif j == " ":
            new_list[count1][count2] = 1 #Blank - 1 for empty cell.
         # else: # Currently you don't have an else, so that makes me guess that you are getting a value you are not expecting.
         else:
             print("ERROR: THERE IS AN ISSUE HERE")
             new_list[count1][count2] = -1

我不知道你的确切输入你可以有二进制数据。如果这是你的情况,那么你将不得不编码/解码相应。你知道吗

我没有遇到你的问题。你知道吗

print(type(new_list[0][0]))
<class "int">

所以您得到了一个意外的输入值。你知道吗

你可以尝试强制一个int

int(new_list[0][0])

如果您需要更多关于打印内容的信息,请使用repr方法。你知道吗

print(repr(new_list[0][0]))

像杰夫·兰格梅尔建议的那样。你知道吗

for i, li in enumerate(new_list):
    for j, item in enumerate(li):
        if item == "-":
            li[j] = 0 #- 0 - Can't go there.
        elif item == "|":
            li[j] = 0 #| 0 - Can't go there.
        elif item == "+":
            li[j] = 0 #+ 0 - Can't go there.
        elif item == " ":
            li[j] = 1 #Blank - 1 for empty cell.
        else:
            print("ERROR")
            li[j] = -1

相关问题 更多 >