该程序将加密消息。它将带有偶数编号索引的所有值并将其放入列表中,并将赔率保留在第一个列表中。最后它会给你一个转换后加密 信息。 示例:ababab成为aaabbb
以上是程序应该做的事情,但是当我实际运行程序时,会给出完全相同的字符串而不是加密版本。
crypt = [] # list to store original answers
original = raw_input("Enter your string: ") # prompts user for their desired string
crypt.append(original) # stores user answers in list crypt
crypt2 = [] # all the items with an even index from list crypt
x = 0
for a in crypt:
if x % 2 == 1: # checks for oddness in the index value
crypt2.append(a) # adds value associated with index to list crypt2
crypt.remove(a) # removes value associated with index from list crypt
x += 1
print crypt + crypt2
我的程序的逻辑部分有问题吗?
答案 0 :(得分:1)
尝试使用print语句来查看循环的行为,您会发现crypt
实际上只包含一个条目。
执行crypt.append(original)
时,它会将整个输入作为加密列表中的单个条目。然后,当你执行for a in crypt
时,只有一次成为整个用户输入,然后循环终止。
如果您想循环使用字符,请使用 crypt.extend 而不是crypt.append
。
答案 1 :(得分:1)
new = ''.join([char for i, char in enumerate(original) if i % 2 == 0])
这也可能有用。
答案 2 :(得分:1)
当你进行循环时:
for a in crypt
你遍历crypt列表中只有1个元素的对象,它是用户编写的字符串。 将程序更改为:
original = raw_input("Enter your string: ") # prompts user for their desired
crypt = [] # list to store original answers
crypt2 = [] # all the items with an even index from list crypt
x = 0
print original
for a in original:
if x % 2 == 1: # checks for oddness in the index
crypt2.append(a) # adds value associated with index to list crypt2
else:
crypt.append(a)
x += 1
print crypt + crypt2
答案 3 :(得分:1)
在crypt.append(original)
之后,crypt
为['ababab']
而不是['a', 'b', 'a', 'b', 'a', 'a']
。此外,除非你知道自己在做什么,否则在迭代它时最好不要改变列表。为了您的目的,迭代original
就足够了。
crypt = []
original = raw_input("Enter your string: ")
crypt = [c for c in original] # convert str to list
crypt2 = []
x = 0
for a in original:
if x % 2 == 1: # checks for oddness in the index value
crypt2.append(a) # adds value associated with index to list crypt2
crypt.remove(a) # removes value associated with index from list crypt
x += 1
print crypt + crypt2
输出:
['a', 'a', 'a', 'b', 'b', 'b']
# if you want 'aaabbb', using print ''.join(crypt + crypt2)
# this will give you 'aaabbb'
一种简单的方法:
>>> original = 'ababab'
>>> original[::2] + original[1::2]
'aaabbb'
>>>