如何将此循环结果作为直接序列(如单个数字)打印?

时间:2017-03-04 21:02:52

标签: python

这是我的循环:

<?php
// Assume $db is a PDO object

$dbh = new PDO('mysql:host=localhost;dbname=populatedropdown', "root", "");

$query = $dbh->query("select * from position"); // Run your query

echo '<form action="populate.php" method="get" name="send3">';
echo '<select name="populate">'; // Open your drop down box



// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
   echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}

echo '</select>';// Close your drop down box

echo '</form>';

?>

<script language="JavaScript">
         function send_input1(){            
          document.send1.input4.value = document.send3.populate.value;
          }
</script>

<form name="send1" action=javascript:send_input1()>
<p><input type=submit value=Enter>
</p><input size=30 name="input4">
</form>

我得到的是:

hi = 567
z = len(str(hi))
his = str(hi)
for i in range(z - 1, -1 ,-1):
    x = his[i],
    print x,

有没有办法让它像这样:

('7',) ('6',) ('5',)

谢谢!

3 个答案:

答案 0 :(得分:2)

试试这个:

print int(str(hi)[::-1])

编辑:与reversedjoin解决方案相比,某些效果基准:

没有int转化:

>>> timeit.timeit("str(hi)[::-1]", setup='hi=567')
0.33620285987854004
>>> timeit.timeit("''.join(reversed(str(hi)))", setup='hi=567')
0.8570940494537354

int转换:

>>> timeit.timeit('int(str(hi)[::-1])', setup='hi=567')
0.6945221424102783
>>> timeit.timeit("int(''.join(reversed(str(hi))))", setup='hi=567')
1.2800707817077637

答案 1 :(得分:1)

只需使用replace''.join

>>> ''.join(reversed(str(hi)))
'765'

答案 2 :(得分:0)

你在第5行有一个额外的逗号。 将您的代码更改为此

hi = 567
z = len(str(hi))
his = str(hi)
for i in range(z - 1, -1 ,-1):
    x = his[i]
    print x,