List to string to lists of letter - python-3.x

I am trying to convert a list of strings to a list of letters/numbers but keeping the length of list the same. Here is my list look like,
a = ["0587828028", "2967480535"]
My code to convert the above list to split the string and save in a new list.
new_a = []
for i in range(len(a)):
new_a += a[i]
And the output is on list,
['0', '5', '8', '7', '8', '2', '8', '0', '2', '8', '2', '9', '6', '7', '4', '8', '0', '5', '3', '5']
Desired output should be 2 list:
['0', '5', '8', '7', '8', '2', '8', '0', '2', '8'] ['2', '9', '6', '7', '4', '8', '0', '5', '3', '5']
Any suggestion is much appreciated, I am very new in python.

Just use the built-in list() iterable expansion:
a = ["0587828028", "2967480535"]
new_a = [list(x) for x in a]
# [['0', '5', '8', '7', '8', '2', '8', '0', '2', '8'],
# ['2', '9', '6', '7', '4', '8', '0', '5', '3', '5']]

Related

While swapping in python using rindex for this specific case why swapping is not happening?

While swapping in python using rindex for this specific case why swapping is not happening? Case-1 is giving correct ans, but not case-2.
Case-1:
S=['1', '1', '1', '2', '1', '1']
S[S.index('1')], S[''.join(S).rindex('2')] = S[''.join(S).rindex('2')], S[S.index('1')]
print(S)
Output: ['2', '1', '1', '1', '1', '1']
Case-2:
S=['2', '1', '1', '1', '1', '1']
S[S.index('1')], S[''.join(S).rindex('2')] = S[''.join(S).rindex('2')], S[S.index('1')]
print(S)
Output: ['2', '1', '1', '1', '1', '1']
But Expected Output: ['1', '2', '1', '1', '1', '1']
Calculate your indices before doing the swap, not in the middle of it:
index1, index2 = S.index('1'), ''.join(S).rindex('2')
S[index1], S[index2] = S[index2], S[index1]

Python3 - Issue when appending to list

I'm new to Python and coding in general (so the following code wont be the cleanest) but coming across the following issue that I can't seem to crack:
Problem
I have 2 CSVs which I'm converting to dictionaries and passing to a function one after another, in order to take the dictionary keys and append them to a list outside of the function, I'm having an issue with:
1 - When printing DataList within the function, it returns a result - when I call it from main.py, returns empty list
2 - The ultimate aim is to remove duplicates after collating data into one list (DataList). Within the function, when I'm appending ClearedValues to DataList, since my lists from the CSVs contain 1-6 in first & 1-7 in second, I'd expect the output (after the function has been run twice) to be:
This is the required DataList within function
[['1', '2', '3', '4', '5', '6'], ['1', '2', '3', '4', '5', '6', '7']]
Instead, there is an additional "7" within DataList[0], see output
cleaner.py:
def DictCleaner(dictionary):
CleanedValues.clear()
for k, v in dictionary.items():
if v != None:
CleanedValues.append(v)
DataList.append(CleanedValues)
print(f"This is the CleanedValues {CleanedValues}”)
print(f"This is the DataList inside the function {DataList}")
main.py
loadCSVs("DataSet1.csv")
print(f"This is the main.py DataList list after 1 run {DataList}")
loadCSVs("DataSet2.csv")
print(f"This is the main.py DataList after the 2 runs {DataList}")
Where CleanedValues and DataLists are lists declared within cleaner.py outside of the function scope
& loadCSVs() is the function that reads the CSV, coverts to a dictionary and returns DictCleaner() with the new dictionary as parameter
Output:
This is the CleanedValues [['1', '2', '3', '4', '5', '6']]
This is the DataList inside the function ['1', '2', '3', '4', '5', '6']
This is the main.py DataList list after 1 run [['1', '2', '3', '4', '5', '6']]
This is the CleanedValues ['1', '2', '3', '4', '5', '6', '7']
This is the DataList inside the function [['1', '2', '3', '4', '5', '6', '7'], ['1', '2', '3', '4', '5', '6', '7']]
This is the main.py DataList after the 2 runs [['1', '2', '3', '4', '5', '6', '7']], ['1', '2', '3', '4', '5', '6', '7']]
Expected output:
This is the DataList inside the function [['1', '2', '3', '4', '5', '6']]
This is the CleanedValues ['1', '2', '3', '4', '5', '6']
This is the main.py DataList list after 1 run [['1', '2', '3', '4', '5', '6']]
This is the DataList inside the function [['1', '2', '3', '4', '5', '6'], ['1', '2', '3', '4', '5', '6', '7']]
This is the CleanedValues ['1', '2', '3', '4', '5', '6', '7']
This is the main.py DataList after the 2 runs [['1', '2', '3', '4', '5', '6'], ['1', '2', '3', '4', '5', '6', '7']]
Any suggestions to optimize code or otherwise are greatly appreciated.

I want to find the highest number using import re .txt

I want to be able to just search for all digits in a text file and find the max number, using the re module. Where do I need to edit my code to accomplish this goal?
The random.txt looks somthing like the following:
Datq15UxkNwMN5zUQhd46J8WeF9RjAq214TlJiQ8EkZvmdOpmBOdd365mICKC67GGvqwbLqV2Gox3n3E5WC1Vq8C22lZ6sL3Ip24untQyw46g2219WlA07GP30PNvc8o3hCb2d283l68mh86RH6gDNbN7kIXmdO4a84hUz73905o3BlR71YCQF985JTz54FRoN32pM8N23YcYd7jv9Ys575UzaH9RZ7sosMdeqnTgnVt0bH99b2P5ilvJ33QaJ6G76VU8vPN
import re
with open('content.txt', 'r',) as f:
contents = f.read()
number = 0
pattern = re.compile(r'\d')
matches = pattern.finditer('content.txt')
for match in matches:
n = int(match)
if saved <= n:
number = int(match)
print(number)
the file just ran once and gave me the answer 0
Try this,
import re
with open('file1.txt', 'r') as f:
data = f.read()
list_of_numbers = re.findall(r'(?:[\d]+)',data)
list_of_numbers = map(int, list_of_numbers)
print(max(list_of_numbers))
Output:
73905 # max number
your list_of_numbers look like this
['15', '5', '46', '8', '9', '214', '8', '365', '67', '2', '3', '3', '5', '1',
'8', '22', '6', '3', '24', '46', '2219', '07', '30', '8', '3', '2', '283', '68',
'86', '6', '7', '4', '84', '73905', '3', '71', '985', '54', '32', '8', '23', '7',
'9', '575', '9', '7', '0', '99', '2', '5', '33', '6', '76', '8']
You are looking for matches within "content.txt" string so there is no match. Also a MatchObject can't be converted to int:
import re
with open('content.txt', 'r',) as f:
contents = f.read()
number = 0
pattern = re.compile(r'\d+')
matches = pattern.finditer(contents)
for match in matches:
n = int(match.group(0))
if number <= n:
number = int(match.group(0))
print(number)

Concatenat very third List items into one item

Hi am trying to concatenate every third item into one item:
I have :
dic = ['3', '3', '⛂', '3', '4', '⛀', '4', '3', '⛀', '4', '4', '⛂']
what i would like is to find a way to create a list of list with every third item
like
dic = [['3', '3', '⛂'], ['3', '4', '⛀'], ['4', '3', '⛀'], ['4', '4', '⛂']]
Here you go!
dic = ['3', '3', '⛂', '3', '4', '⛀', '4', '3', '⛀', '4', '4', '⛂']
lst=[]
for i in range(0,len(dic),3):
lst.append(dic[i:i+3])
print(lst)
Output:
[['3', '3', '⛂'], ['3', '4', '⛀'], ['4', '3', '⛀'], ['4', '4', '⛂']]

update nested list with user input

A function in a program I'm working on takes a list of quiz scores, and asks the user to input the name of a round and the score. If the round already exists, it appends the new score to the existing list, otherwise it adds the round and its score to the top-layer of the list:
lines = [['geography', '8', '4', '7'],
['tv and cinema', '4', '4', '8', '7', '7'],
['all creatures great and small', '7', '8'],
['odd one out', '4', '7'],
['music', '3', '5', '8', '8', '7'],
['how many', '4']]
roundName = input("Enter the name of the round to add: ")
score = input("Enter the score for that round: ")
for line in lines:
if roundName in line:
line.append(score)
lines.append([roundName, score])
#for line in lines:
# if line[0] == roundName.lower().strip():
# existingRound = lines.index(line)
# lines[existingRound].append(score)
# else:
# newRound = [roundName, score]
# lines.append(newRound)
The commented part represents my first few attempts. Entering how many, 3 should result in
lines = [['geography', '8', '4', '7'],
['tv and cinema', '4', '4', '8', '7', '7'],
['all creatures great and small', '7', '8'],
['odd one out', '4', '7'],
['music', '3', '5', '8', '8', '7'],
['how many', '4', '3']]
#actually results, in
[['geography', '8', '4', '7'],
['tv and cinema', '4', '4', '8', '7', '7'],
['all creatures great and small', '7', '8'],
['odd one out', '4', '7'],
['music', '3', '5', '8', '8', '7'],
['how many', '4', '3'],
['how many', '3']]
I can't get the logic in the loop right. Where am I going wrong?
for line in lines:
if roundName in line:
line.append(score)
lines.append([roundName, score])
Right here you're adding the new round to lines regardless of whether if it was present in lines already. Just use a boolean to indicate if adding to lines is needed and then change appending the new round to lines to a conditional:
add = True
for line in lines:
if roundName in line:
line.append(score)
add = False
if add: lines.append([roundName, score])
If order doesn't matter though it would be much easier to use a dictionary:
lines = {'geography':['8', '4', '7'], 'tv and cinema': [...] ...}
roundName = input("Enter the name of the round to add: ")
score = input("Enter the score for that round: ")
if roundName in lines: lines[roundName].append(score)
else: lines[roundName] = [score]

Resources