C++;给python初学者 我对Python完全陌生,我有C++的代码片段: do { cout << "Make sure the number of digits are exactly 12 : "; cin >> input ; } while((input.length()) != 12 );
以上部分已解决强>C++;给python初学者 我对Python完全陌生,我有C++的代码片段: do { cout << "Make sure the number of digits are exactly 12 : "; cin >> input ; } while((input.length()) != 12 );,python,python-3.x,Python,Python 3.x,以上部分已解决 另外,另一个C++片段是:输入是字符串< /强> for (int i = 0; i < 12 ; i++) { code[i] = input.at(i) - '0'; } 所以,我遇到的问题是,我不知道如何初始化数组 int code[12] ; 在python中应该是怎样的,这样我就可以执行这段代码了!如上所述: int code[12] ; for (int i = 0; i < 12 ; i++) {
另外,另一个C++片段是:<强>输入是字符串< /强>
for (int i = 0; i < 12 ; i++)
{
code[i] = input.at(i) - '0';
}
所以,我遇到的问题是,我不知道如何初始化数组
int code[12] ;
在python中应该是怎样的,这样我就可以执行这段代码了!如上所述:
int code[12] ;
for (int i = 0; i < 12 ; i++)
{
code[i] = input.at(i) - '0';
}
int代码[12];
对于(int i=0;i<12;i++)
{
代码[i]=输入。在(i)-“0”;
}
对于第一个代码段,您可以更改:
print("Make sure the number of digits are exactly 12: ")
input = raw_input()
致:
您也不需要check
变量,只需执行以下操作:
if len(input) == 12:
break
注意在IF语句之后我是如何包含一个:
(相等性测试也必须是=
,而不是!=
)。然后,如果条件为True
,则执行决策后进一步缩进的任何内容
对于第二个代码段,可以使用int()
和str()
函数将整数转换为字符串(以及字符串转换为整数)。例如
>>> a = '012345678912'
>>> len(a) == 12
True
>>> b = int(a)
>>> print b
12345678912
>>> str(b)
'12345678912'
首先
关于你的第一个问题:
while True:
print "Make sure the number of digits are exactly 12 : "
x = input()
if len(str(x)) == 12:
break
Python对空格很敏感,并且使用制表符和空格(而不是括号)管理方法。你还缺了一个冒号
对于第二个问题,代码看起来像是将字符转换成数字。您只需执行类型转换:
for i in range(12):
code[i] = int(x[i])
在python中,有一些更简单的方法可以将数字字符串解析为其组成值,例如
code.append(int(input[ind]))
不过,我提供的翻译与代码的目的无关[可能包括字母等]
python中的变量“code”是列表而不是数组当然如何初始化数组?与int code[12]类似,然后执行第二部分?您可以使用以下命令创建数组:
myList=[]
。然后使用.append()
函数(即myList.append(3)
)将项目添加到列表中。我应该如何初始化代码数组?或者我们在python中不这样做?请注意,将代码从一种语言“翻译”到另一种语言并不能很好地工作,因为在一种语言中很有意义的事情在另一种语言中可能效率低下且无法阅读。此外,如果您有两个问题,请分别发布它们,而不是附加到一个问题上。它将吸引更多的人来回答,并使它成为对其他人更有用的资源。
while True:
print "Make sure the number of digits are exactly 12 : "
x = input()
if len(str(x)) == 12:
break
for i in range(12):
code[i] = int(x[i])
do
{
cout << "Make sure the number of digits are exactly 12 : ";
cin >> input ;
} while((input.length()) != 12 );
int code[12] ;
for (int i = 0; i < 12 ; i++)
{
code[i] = input.at(i) - '0';
}
while True:
input = raw_input("Make sure the number of digits are exactly 12 : ")
if len(input) == 12:
break
code = []
for ind in range(0,12):
code.append(ord(input[ind]) - ord('0'))
code.append(int(input[ind]))