質問

So I have an algorithm which takes a list of 10 characters and creates 10 new lists of characters each with on e character "mutated".

(I have to use a list of characters rather than a string because a string object does not support item assignment)

For example, this would be the desired output:

Input word: H E L L O W O R L D .

H I L L O W O R L D .

H U L L O W O R L D .

H E L L O K O R L D .

And so forth.

Now with my program I get a weird output.

import random

def generation(myList2):
    data=[]

    for a in range(10):
        data.append(myList2)

        data[a][random.randint(0,9)]=random.choice("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".split())

    return data

myName=raw_input()

data=generation(myName.split())

for i in data:
    print(i)

OUTPUT:

H I L K E F G J E .

H I L K E F G J E .

H I L K E F G J E .

H I L K E F G J E .

H I L K E F G J E .

And so forth.

It seems that the parameter in my function (myList2) is somehow not remaining constant and is changing as the list "data" changes.

Does anybody know why this is happening or can give some sort of reason or solution to my problem?

役に立ちましたか?

解決

Very easily, change your generation method to:

for a in range(10):
    data.append(myList2[:])

instead of:

for a in range(10):
    data.append(myList2)

This is so that each element in data does not contain reference to the same myList2 object. The myList2[:] creates a copy of the object.

Also, instead of

for i in data:
    print(i)               #prints list of characters in a not-so-nice format

do:

for i in data:
    print(''.join(i))      #prints string

他のヒント

You are appending a reference to the result list, and actually all you do is manipulating the same list over and over again, appending a new reference of it to the result list.

If you want to have a list containing all 'mutations', you need to clone the list at each iteration. (The link provides some useful solutions regarding cloning a list in python). As you can see in the link, probably the easiest method to clone a list is newCopy = myList2[:]

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top