isinstance()无法按照我认为的方式工作

时间:2019-10-22 20:47:36

标签: python

我的程序要求用户输入两个元素的列表,因此,为了检查是否满足这些条件,我使用了以下代码:

start = input('Enter you start location.\nE.g. Enter "[2,5]" for x-coordinate 2 and y-coordinate  
             5.')
while isinstance(start, list) == False or len(start) != 2:
     start = input('Try again.')

无论我输入什么内容,都永远不会退出while循环。为什么?

2 个答案:

答案 0 :(得分:2)

因为您的start = "[2,5]"变量原来是一个字符串:2,3,它不是列表。您可以要求用户输入"2,3", 那么您得到start.split(',')。然后,您可以使用 //Connect to our MySQL database using the PDO extension. $pdo = new PDO('mysql:host=localhost;dbname=finalzakat', 'root', ''); //Our select statement. This will retrieve the data that we want. $sql = "SELECT id, city_name FROM cities"; //Prepare the select statement. $stmt = $pdo->prepare($sql); //Execute the statement. $stmt->execute(); //Retrieve the rows using fetchAll. $users = $stmt->fetchAll(); ?> <?php (isset($_POST["city"])) ? $city = $_POST["city"] : $city="user"; ?> <select class="form-control" id="city" name="city" value="<?php echo $city; ?>"> <?php foreach($users as $user): ?> <option <?php if ($city == 'user' ) echo 'selected' ; ?> value="<?= $user['city_name']; ?>"><?= $user['city_name']; ?></option> <?php endforeach; ?> </select>

将其拆分为列表

答案 1 :(得分:1)

绝对不建议使用明显的安全风险,但是您可以使用eval

start = eval(input('Enter you start location.\nE.g. Enter "[2,5]" for x-coordinate 2 and y-coordinate 5.'))

首选方法是使用分割,但是在这种情况下,请用户输入以逗号分隔的坐标。

start = input('Enter you start location.\nE.g. Enter "2,5" for x-coordinate 2 and y-coordinate 5.')
start = start.split(",")

按照@soyapencil注释的要求进行编辑

inp_str = input('Enter you start location.\nE.g. Enter "[2,5]" for x-coordinate 2 and y-coordinate 5.')
start = [int(i) for i in iter(eval(inp_str,{}))]