I am trying to append a list of 4 letters in my number as a [[a, b, c, d]] type of list.
I am looping through a list and appending the letter to a temp list and then appending it to my main list to make it into a matrix. However, the main list is only storing the number (8, 26) for some reason
ciphertext = "asfgasgsaga"
counter = 0
templist = []
xyz = []
for abc in ciphertext:
if(counter == 5):
print(templist)
xyz.append(templist)
templist.clear()
counter = 0
else:
templist.append(abc);
counter += 1
print(xyz)
The result is for some reason giving [[8, 26]]
The result is not the same as your expected because there some concepts that you need to know about objects in Python:
Immutable Objects: int, float, complex, string, tuple, frozen set, bytes. These kind of data types can't be changed the value after it is created. So that when we assign to another variable, it will copy the value to new variable. E.g:
a = 123
b = a
a = 456
print(b) #123
Mutable Objects: list, dict, set, byte array. These can be changed the value after it is created. And when you assign to another variable, it basically just assign the reference to previous variable like so:
a = []
b = a
a.append(123)
print(b) #[123]
So back to your problem, you're using list to create a list with 4 characters and then append it into another list, it's not append the expected list but instead a reference to it. That's why you got unexpected result.
And about the logic of your code, there are something go wrong, because when counter you will miss 1 character. You actually can switch to use slicing in Python:
ciphertext = "asfgasgsaga"
xyz = [ciphertext[start:start + 4] for start in range(0, len(ciphertext), 4)]
print(xyz) #['asfg', 'asgs', 'aga']
I'm using List Comprehension to append to xyz instead of call append function, create step like: 0:4, 4:8, 8:12, ... voila
Hope that helpful for you.
Just as #zvone says, don's use the same array and clear it, because they ref the same memory;
ciphertext = "asfgasgsaga"
counter = 0
templist = []
xyz = []
for abc in ciphertext:
if(counter == 4):
print(templist)
xyz.append(templist)
templist = [] # <--- use a new empty array
counter = 0
else:
templist.append(abc);
counter += 1
print(xyz)
Also, the correct logic(handle the letters less than 4) should be:
ciphertext = "asfgasgsaga"
counter = 0
templist = []
xyz = []
for abc in ciphertext:
templist.append(abc);
counter += 1
if(counter == 4):
print(templist)
xyz.append(templist)
templist = []
counter = 0
if templist:
xyz.append(templist)
print(xyz)
Just see #Toan Quoc Ho's answer, which should make more sense. Just leave the answer here to compare your origin logic.
Related
I'm a freshie. I would like to convert a numeric string into int from a sublist in Python. But not getting accurate results. 😔
countitem = 0
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
for list in list_samp:
countitem =+1
for element in list:
convert_element = int(list_samp[countitem][0])
list_samp[countitem][1] = convert_element
You can do it like this:
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
me = [[int(u) if u.isdecimal() else u for u in v] for v in list_samp]
print(me)
The correct way to do it:
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
list_int = [[int(i) if i.isdecimal() else i for i in l] for l in list_samp]
print(list_int)
Let's go through the process step-by-step
countitem = 0
list_samp = [['1','2','blue'],['1','66','green'],['1','88','purple']]
#Let's traverse through the list
for list in list_samp: #gives each list
for i in range(len(list)): # get index of each element in sub list
if list[i].isnumeric(): # Check if all characters in the string is a number
list[i] = int(list[i]) # store the converted integer in the index i
Im new to python and hit a wall with my last print in my program
I got a list of numbers created with math int(numbers that when printed looks like this
[0, 0, 0, 0] #just with random numbers from 1 - 1000
I want to add text in front of every random number in list and print it out like this
[Paul 0 Frederick 0 Ape 0 Ida 0]
Any help would be appreciated. Thanks !
Sounds like you want to make a dictionary. You could type:
d = dict()
d["Paul"] = random.randint(1,100)
....
print(d)
#output: {"Paul":1, "Fredrick":50, "Ape":25, "Ida":32}
Alternatively there is nothing stopping you from using strings and integers in the same list! Python is not strongly statically typed.
If you have a list of numbers [45,5,59,253] and you want to add names to them you probably need a loop.
nums = [45,5,59,253]
names = ["Paul", "Frederick", "Ape", "Ida"]
d = dict()
i = 0
for n in nums:
d[names[i]] = n
i+=1
or if you wanted a list
nums = [45,5,59,253]
names = ["Paul", "Frederick", "Ape", "Ida"]
list = [x for y in zip(names, nums) for x in y]
You'd have to turn your random integers into strings and add them to the text (string) you want.
Example:
lst=[]
x = str(randint(0,1000))
text = 'Alex'
final_text = text+' '+x
lst.append(final_text)
Just added the space like in your example. It'll just be a little more complex to access the numbers if you do it this way.
I know there is quite a number of similar questions on stackoverflow but they don't seem to be solving my problem. If you look at my code below, you can see that I am creating a temp list of ads called "tempAdList" and when the if condition evaluate true I am creating a list of lists called "ad_list". I am appending to "ad_list" so I am expecting that everytime the "if statement" evaluates true a new list of 4 ads is appended to "ad_list" but for whatever reason I am getting below output which is not what i am looking for. what am I doing wrong here?
ads = Advert.objects.all()
counter = 1
tempAdList = []
ad_list = []
for i, ad in enumerate(ads):
tempAdList.append(ad)
if counter == 4:
# print(tempAdList)
ad_list.append(tempAdList)
print(ad_list)
tempAdList.clear()
counter = 0
counter += 1
adsNum = len(ads)
# print("i = {} and adsNum = {}".format(i, adsNum))
if i == adsNum -1 and adsNum % 4 != 0:
ad_list.append(tempAdList)
output:
Using the clear-method on a list also affects all references to it, e.g.
>>a = [1, 2, 3]
>>b = a
>>a.clear()
>>print('a =',a)
a = []
>>print('b =',b)
b = []
So what you are doing in ad_list.append(tempAdList) is to repeatedly add references to the same object to ad_list, i.e. each time you update tempAdList, the same update is done for each of those references. What you really want to do is reset tempAdList with a new object, so replace tempAdList.clear() with tempAdList=[].
If you just want a list of lists, where inner lists are having 4 elements.
You can try something like :
new_list = [ads[i:i+4] for i in range(0, len(ads), 4)]
Every time you do tempAdlist.clear(), you cleared all elements of the list. But because you appended the list to ad_list, you basically cleared it there too. so you have one less list. This is because of the nature of lists being referenced instead of recreated. What you want is to create a list from tempAdlist when appending, like so: ad_list.append(list(tempAdlist)) this way it will be a whole new list from the tempAdlist. Essentially your code becomes:
ads = Advert.objects.all()
counter = 1
tempAdList = []
ad_list = []
for i, ad in enumerate(ads):
tempAdList.append(ad)
if counter == 4:
# print(tempAdList)
ad_list.append(list(tempAdList))
print(ad_list)
tempAdList.clear()
counter = 0
counter += 1
adsNum = len(ads)
# print("i = {} and adsNum = {}".format(i, adsNum))
if i == adsNum -1 and adsNum % 4 != 0:
ad_list.append(list(tempAdList))
How do I code a function in python which can:
iterate through a list of word strings which may contain duplicate words and referencing to a dictionary,
find the word with the highest absolute sum, and
output it along with the corresponding absolute value.
The function also has to ignore words which are not in the dictionary.
For example,
Assume the function is called H_abs_W().
Given the following list and dict:
list_1 = ['apples','oranges','pears','apples']
Dict_1 = {'apples':5.23,'pears':-7.62}
Then calling the function as:
H_abs_W(list_1,Dict_1)
Should give the output:
'apples',10.46
EDIT:
I managed to do it in the end with the code below. Looking over the answers, turns out I could have done it in a shorter fashion, lol.
def H_abs_W(list_1,Dict_1):
freqW = {}
for char in list_1:
if char in freqW:
freqW[char] += 1
else:
freqW[char] = 1
ASum_W = 0
i_word = ''
for a,b in freqW.items():
x = 0
d = Dict_1.get(a,0)
x = abs(float(b)*float(d))
if x > ASum_W:
ASum_W = x
i_word = a
return(i_word,ASum_W)
list_1 = ['apples','oranges','pears','apples']
Dict_1 = {'apples':5.23,'pears':-7.62}
d = {k:0 for k in list_1}
for x in list_1:
if x in Dict_1.keys():
d[x]+=Dict_1[x]
m = max(Dict_1, key=Dict_1.get)
print(m,Dict_1[m])
try this,
key, value = sorted(Dict_1.items(), key = lambda x : x[1], reverse=True)[0]
print(f"{key}, {list_1.count(key) * value}")
# apples, 10.46
you can use Counter to calculate the frequency(number of occurrences) of each item in the list.
max(counter.values()) will give us the count of maximum occurring element
max(counter, key=counter.get) will give the which item in the list is
associated with that highest count.
========================================================================
from collections import Counter
def H_abs_W(list_1, Dict_1):
counter = Counter(list_1)
count = max(counter.values())
item = max(counter, key=counter.get)
return item, abs(count * Dict_1.get(item))
I would like my program to print every other letter in the string "welcome".
like:
e
c
m
Here is the code I have so far:
stringVar = "welcome"
countInt = 7
count = 0
oneVar = 1
twoVar = 2
showVar = stringVar[oneVar:twoVar]
for count in range(countInt):
count = count + 1
oneVar = oneVar + count
twoVar = twoVar + count
print(showVar)
Though it only shows the 2nd letter "e".
How can I get the variables oneVar and twoVar to update so that the range changes for the duration of the loop?
There is a built in notation for this, called "slicing":
>>> stringVar = "welcome"
>>> print(stringVar[::2])
wloe
>>> print(stringVar[1::2])
ecm
stringVar is iterable like a list, so the notation means [start : end : step]. Leaving any one of those blank implicitly assumes from [0 : len(stringVar) : 1]. For more detail, read the linked post.
Another more complex way of the doing the same would be
string_var = "welcome"
for index, character in enumerate(string_var, start=1): # 'enumerate' provides us with an index for the string and 'start' allows us to modify the starting index.
if index%2 == 0:
print character
Why its not working in your snipet:
Even though you increase oneVar and twoVar inside the loop, there is no change in the showVar as showVar is string which is immutable type, and its printing stringVar[1:2] which is e the 2nd index of welcome:
Just to fix your snippet:
You can just try like this;
stringVar = "welcome"
countInt = 7
for count in range(1,countInt,2):
print count, stringVar[count]
Output:
e
c
m