如果用户列表中的所有元素都是lis,则返回True

2024-10-01 17:21:34 发布

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

已解决

我的练习是编写一个名为list\u check的函数,该函数接受来自用户的列表,如果userlist中的每个元素本身也是一个列表,则返回True。你知道吗

底线是我想看到一个使用用户输入解决这个问题的工作示例,这比自己提供列表更困难。你知道吗

这是我最近一次接受用户对列表的输入:

userlist = []
number_of_elements = int(input("Enter the number of elements in your list: "))

for i in range(0, number_of_elements):
    element = input().split()
    userlist.append(element)

if all(isinstance(element, list) for element in userlist):
    print("True")
else:
    print("False")

无需用户输入的工作代码如下:

customlist = [[1,2,3],[2,3,4], False]

def list_check(customlist):
    answer = all(type(l) == list for l in customlist)
    print(answer)

list_check(customlist)

谢谢你的帮助。 -日本


Tags: of函数用户intruenumber列表for
2条回答

这是因为.split()将始终返回一个列表dog'.split()=['dog']。你知道吗

解决方案(优化)

number_of_elements = int(input("Enter the number of elements in your list: "))

output = True
for _ in range(number_of_elements):
    element = input().split()
    if len(element) == 1: output = False

print(output)
def listcheck():
    y = (input("Enter your lists: \n"))
    if y[0] !="[" or y[1] !="[":
        print("false, you entered data not starting with [[")
        return False
    if y[len(y)-1] !="]" or y[len(y)-2] !="]":
        print("false, you entered data not ending with ]]")
        return False
    import ast
    z = ast.literal_eval(y)
    def innerlistcheck(alist):
        for x in range(0, len(alist), 1):
            if type(alist[x]) != list:
                print("false, " + str(alist[x]) + " is not a list")
                return False
        print("true")
        return True
    innerlistcheck(z)

listcheck()

我想这也许是你问题的答案。 最困难的部分是看如何将字符串转换成我从这里偷来的列表:Convert string representation of list to list

相关问题 更多 >

    热门问题