Question

Here I am taking a string and iterating through it to retrieve the individual letters. After I get them, I run them through a dictionary which replaces the letter with a numerical value. In the final section of code, I am attempting to put the numerical values into a single list, like this [45, 67, 86, 79] and so on.

pad_length = int(raw_input("How long will your one time pad be?"))
otp = one_time_pad_generator(pad_length)
otp = otp.upper()
print otp
# Defining One Time Pad


base_dict = {"A":1, "B":2, "C":3, "D":4, "E":5, "F":6, "G":7, "H":8, "I":9, "J":10, "K":11, "L":12, "M":13, 
"N":14, "O":15, "P":16, "Q":17, "R":18, "S":19, "T":20, "U":21, "V":22, "W":23, "X":24, "Y":25, "Z":26}
for i in otp:
    important_list = [base_dict[i]]

(One time pad generator simply takes a number and outputs that many randomly generated letters)

But instead of a single list with multiple integers within, I get

[45] [67] [86] [79]

Each number is individually bracketed, and printed vertically. How do I get them all into the same list?

Was it helpful?

Solution 2

You are not building one list, you are continually replacing your list with a new one:

for i in otp:
    important_list = [base_dict[i]]

Here the [...] syntax creates a new list object with just one element.

You could create the object just once, empty, then use list.append() to add elements:

important_list = []
for i in otp:
    important_list.append(base_dict[i])

or use a list comprehension:

important_list = [base_dict[i] for i in otp]

The dictionary is a little overkill here though; you could use ord() to get the ASCII codepoint instead and subtract 64:

important_list = [ord(i) - 64 for i in otp]

as ord('A') is 65.

OTHER TIPS

You should use list comprehension like this

important_list = [base_dict[i] for i in otp]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top