(you can view the source here)
So I am running in to a issue.
Lets say I have a list named mylist
.
When I add a word to the list, for example cat
, it's not ['cat']
but instead ['c', 'a', 't']
. And my code has a function where it wants to eliminate combinations its already tried, so you can see how this is a problem. Any help?
here is the code:
import os
from random import randrange
from colorama import *
def clear():
os.system('clear')
realWords = []
fakeWords = []
letters = ['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']
words = []
sentence = ""
def testAWord():
global fakeWords
global realWords
word = ""
for i in range(randrange(10)):
word = letters[randrange(len(letters))]
for i in fakeWords:
if word == i:
print(Fore.RED "Already in database: FAKE")
break
for i in realWords:
if word == i:
print(Fore.LIGHTBLUE_EX "Already in database: REAL")
break
print(Fore.GREEN "Lets test a word. Is " Fore.LIGHTGREEN_EX word Fore.GREEN " a word?")
isItAWord = input()
if isItAWord == "y":
realWords = str(word)
elif isItAWord == "n":
fakeWords = str(word)
# if isItAWord == "m":
# sent = makeASentence()
# print(sent)
if isItAWord == "v":
print(Fore.GREEN str(realWords))
print(Fore.RED str(fakeWords))
input()
clear()
while(True):
testAWord()
CodePudding user response:
Use the .append()
function:
if isItAWord == "y":
realWords.append(str(word))
elif isItAWord == "n":
fakeWords.append(str(word))
This will add the full word into your list, as opposed to the individual characters.
CodePudding user response:
realWords = str(word)
is equivalent to realWords.extend(str(word))
, which appends all elements from the iterable str(word)
to the list one by one.
Example:
>>> realWords = []
>>> word = 'foo'
>>> realWords = str(word)
>>> realWords
['f', 'o', 'o']
What you want is realWords.append(str(word))
. Same goes for the handling of fakeWords
.
You can also omit str
in str(word)
if word
is already a string (I didn't check).
CodePudding user response:
You cannot add elements to an array by simply " ="ing your element to the array, instead you need to [array].append([element]).
.append(), appends the element to the end of the array.
So try changing:
if isItAWord == "y":
realWords = str(word)
elif isItAWord == "n":
fakeWords = str(word)
to:
if isItAWord == "y":
realWords.append(str(word))
elif isItAWord == "n":
fakeWords.append(str(word))