错误列表对象仅在云解释器中没有属性拆分 VSCode 在接受字符串作为输入时正确运行代码

问题描述 投票:0回答:1

我正在构建一个函数,将输入字符串拆分为两个列表(因为它们是数字),并找到两者之间的交集。我的代码在 VSCode(Desktop) Python 3.12 中运行良好,没有错误,但是当我尝试在 Cloud(Coderbytes) 上运行它时,返回一个错误,指出输入是一个列表,因此它没有 split 属性...真的令人困惑

def FindIntersection(strArr):
    # Split the input string using '"' and extract the lists
    strArr = strArr.split('"')

    
    # The lists are at indices 1 and 3 after splitting by '"'
    first = strArr[1]
    second = strArr[3]
    
    # Convert the strings to lists of integers
    One = [int(x) for x in first.strip("[] ").split(", ")]
    Two = [int(x) for x in second.strip("[] ").split(", ")]
    
    # Find the intersection using set intersection
    intersection = list(set(One).intersection(Two))
    
    # Create a comma-separated string from the intersection

    strArr = ", ".join(map(str, intersection))
    
    # Return the result
    return strArr

# Keep this function call here
print(FindIntersection(input()))

如果我输入这个字符串作为输入

[“1,3,4,7,13”,“1,2,4,13,15”]

输出为:1,4,13

并且在 VSCode 桌面版本中没问题,但在 Coderbytes Cloud 解释器收到错误

* 回溯(最近一次调用最后一次):

文件“/home/glot/main.py”,第 23 行,位于 print(FindIntersection(["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]))

文件“/home/glot/main.py”,第 3 行,在 FindIntersection 中 strArr = strArr.split('"')

AttributeError:“list”对象没有属性“split”*

所以我的问题是为什么 Coderbytes 将字符串识别为列表? 当 VSCode 验证它时?

python string list error-handling
1个回答
0
投票

Coderbyte 似乎在将您提供的输入传递给代码之前对其进行预处理。

因此,它将

["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]
视为
list
而不是
string
(在 VS-Code 中)。

这是更新后的代码:我删除了“拆分输入字符串”部分。

def FindIntersection(strArr):
    # The lists are at indices 1 and 3 after splitting by '"'
    first = strArr[0]
    second = strArr[1]
    
    # Convert the strings to lists of integers
    One = [int(x) for x in first.strip("[] ").split(", ")]
    Two = [int(x) for x in second.strip("[] ").split(", ")]
    
    # Find the intersection using set intersection
    intersection = list(set(One).intersection(Two))
    
    # Create a comma-separated string from the intersection
    strArr = ", ".join(map(str, intersection))
    
    # Return the result
    return strArr
# Keep this function call here
print(FindIntersection(input()))

© www.soinside.com 2019 - 2024. All rights reserved.