This question already has answers here:
Apply function to each element of a list
(4 answers)
How do I make a flat list out of a list of lists?
(34 answers)
Closed 1 year ago.
I have a very simple list where it looks like this:
['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65', '08 14 31 58 68', '01 10 44 47 56']
What I would like to do is to split the values within each list where the values are displayed as follows:
[20,32,35,47,64,15,17,25,32,53,07,10,12,61,65,..]
myvallist = myvalues.split(" ")
print (myvallist)
For some reason, when I attempt to use the .split(), pyCharm is throwing an error.
Traceback (most recent call last):
File "C:\Users\VFARETR.CENTRAL\Desktop\pyCharm\megaTest", line 25, in <module>
myvallist = myvalues.split(" ")
AttributeError: 'list' object has no attribute 'split'
Any help would be great!
You're trying to split the list, not the string. Try this:
input_list = ['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65', '08 14 31 58 68', '01 10 44 47 56']
complete_list = []
for sub_list in input_list:
current_items = sub_list.split()
complete_list.extend([i for i in current_items])
It says so because your list consists of strings. You have to acces the string inside the list before you split the string.
mylist = ['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65',
'08 14 31 58 68', '01 10 44 47 56']
myvallist = []
for item in mylist:
myvallist += item.split(' ') # adds the numbers of the current string to myvallist
print(myvallist)
I don't know if you want the entries to be integers or strings but here's a solution with them as strings.
my_list = ['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65', '08 14 31 58 68', '01 10 44 47 56']
my_new_list = [item for sublist in [item.split(" ") for item in my_list] for item in sublist]
The inner list comprehension splits each string by spaces and then the outer list comprehension then flattens the array produced.
Related
arr(['36 36 30','47 96 90','86 86 86']
I want to store and print the values like this,
36
36
30
47
...
How do I do this using python?
the simplest way is to use for and str.split()
arr=['36 36 30','47 96 90','86 86 86']
for block in arr:
cells = block.split()
for cell in cells:
print(cell)
prints
36
36
30
47
96
90
86
86
86
you can also use a list comprehension like so, which returns the same result.
print("\n".join([ele for block in arr for ele in block.split()]))
You can use lists and split in python. Try in this way:
arr = ['36 36 30','47 96 90','86 86 86']
for i in arr:
elems = i.split()
for elem in elems:
print(elem)
We can try the following approach. Build a single string of space separated numbers, split it, then join on newline.
inp = ['36 36 30', '47 96 90', '86 86 86']
output = '\n'.join(' '.join(inp).split())
print(output)
This prints:
36
36
30
47
96
90
86
86
86
def leesFormulier(l1):
index = 0
lres = []
for j in range(len(l1)):
for k in range(0,9,2):
if l1[j][k] == 'X':
lres.append(index+1)
index += 1
else:
index += 1
return lres
print(leesFormulier(l1 = ['1 X 3 4 X', 'X 7 X X 10', '11 12 13 14 15', '16 17 18 19 20', '21 22 23 24 25', '26 27 28 29 30', '31 32 33 34 35', '36 37 38 39 40', '41 42 43 44 X']))
result : [2, 5, 6, 8, 9]
Hello everybody,
I'm making an exercise on Python and I have to find the indices of where you can find the 'X'. And I solved it for the most part but the only problem I'm having is the last 'X' that won't be recognized. I put it in Pythontutor and there I could see that on the last time going through the for loops that it goes to the last k for loop but it doesn't check it but instead goes immediately to the j for lus and then ends the iteration and goes to the return part. I don't know what I'm doing wrong, would appreciate it if somebody could help me out.
Thanks in advance!
Don't need all those indexes or nested loops for this problem and you can simplify it a lot
def lessFromulier(l1):
lres = []
new_string = " ".join(l1).split(" ")
for i, letter in enumerate(new_string):
if letter == "X":
lres.append(i+1)
return lres
test = [
"1 X 3 4 X",
"X 7 X X 10",
"11 12 13 14 15",
"16 17 18 19 20",
"21 22 23 24 25",
"26 27 28 29 30",
"31 32 33 34 35",
"36 37 38 39 40",
"41 42 43 44 X",
]
print(lessFromulier(test))
which gives this output
[2, 5, 6, 8, 9, 45]
Your input is really weird to me, but here is a solution to your question
def leesFormulier(l1):
index = 0
lres = []
for i in range(len(l1)):
for j in range(len(l1[i])):
c = l1[i][j]
if c == ' ':
continue
if c == 'X':
index += 1
lres.append(index)
else:
index += 1
return lres
print(leesFormulier(l1 = ['1 X 3 4 X', 'X 7 X X 10', '11 12 13 14 15', '16 17 18 19 20', '21 22 23 24 25', '26 27 28 29 30', '31 32 33 34 35', '36 37 38 39 40', '41 42 43 44 X']))
I have a list of lists that I am trying to write to columns instead of rows. My list looks like this:
['31 32 31 8', '31 31 32 8', '31 31 31 8', '31 32 31 31']
I want it to llok like this:
31 31 31 31
32 31 31 32
31 32 31 31
8 8 8 31
I can get a nice print in rows like this:
with open("text.csv", 'w') as f:
for x in zip(contents):
f.write('\t'.join(x)+'\n')
What I would like to do is get this data in columns
You may use zip() for this. Firstly convert your list of string to list of list using str.split(), then iterate over ziped list. Below is the sample code:
>>> my_list = ['31 32 31 8', '31 31 32 8', '31 31 31 8', '31 32 31 31']
>>> my_list_list = [s.split() for s in my_list]
>>> for item in zip(*my_list_list):
... print item
...
('31', '31', '31', '31')
('32', '31', '31', '32')
('31', '32', '31', '31')
('8', '8', '8', '31')
Alternatively, numpy is really good for this kind of stuff.
If you have
test = numpy.array([[31,32,31,8], [31,31,32,8], [31,31,31,8], [31,32,31,31]]
then you can access the first column by saying
test[:,0] which returns array([31, 31, 31, 31])
Use the csv module to output the data once you've massaged it into shape with zip():
import csv
# data is a list of lists
data = [s.split() for s in ['31 32 31 8', '31 31 32 8', '31 31 31 8', '31 32 31 31']]
with open('text.csv', 'w') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerows(zip(*data))
This results in a CSV file which uses tab as the delimiter that looks like this:
31 31 31 31
32 31 31 32
31 32 31 31
8 8 8 31
Faultysats=[{'G11': '16 01 13 09 43 50.0000000'},
{'G11': '16 01 13 09 43 51.0000000'},
{'G03': '16 01 13 09 43 52.0000000'}]
SATS=['G01', 'G03', 'G04', 'G08', 'G11', 'G19', 'G28', 'G32']
EPOCH='16 01 13 09 43 51.0000000'
I have a these lists- faultysats, a list of dictionaries containing varying satellite and epoch times; SATS, a list containing sats; and EPOCH, a time value.
If a satellite from faultysats (e.g'G11') appears in SATS AND its corresponding epoch (eg. '16 01 13 09 43 50.0000000') from faultysats appears in EPOCH, I want to know which index the satellite is at in the SATS list.
Hope that makes sense, im struggling because i dont know how to ascertain varying values in a list of dictionaries. Is there a certain operator that deals with extracting data from a list of sats?
To get a list of the indexes you could use:
Faultysats=[{'G11': '16 01 13 09 43 50.0000000'},
{'G11': '16 01 13 09 43 51.0000000'},
{'G03': '16 01 13 09 43 52.0000000'}]
SATS=['G01', 'G03', 'G04', 'G08', 'G11', 'G19', 'G28', 'G32']
EPOCH='16 01 13 09 43 51.0000000'
indexes = []
for i in range(0, len(Faultysats)):
for key in Faultysats[i]:
if (key in SATS) and (Faultysats[i][key] == EPOCH):
indexes.append(i)
print(indexes)
How about this:
Get first the list of dictionaries's keys whose corresponding value is equal to EPOCH then get the index of that key from SATS:
>>> Faultysats=[{'G11': '16 01 13 09 43 50.0000000'},
{'G11': '16 01 13 09 43 51.0000000'},
{'G03': '16 01 13 09 43 52.0000000'}]
>>> SATS=['G01', 'G03', 'G04', 'G08', 'G11', 'G19', 'G28', 'G32']
>>> EPOCH='16 01 13 09 43 51.0000000'
>>> f = [k for d in Faultysats for k,v in d.items() if EPOCH == v]
>>> indx = [SATS.index(x) for x in f]
>>>
>>> indx
[4]
First, let's get a list of all satellites from Faultysats that are in SATS and have the EPOCH timestamp.
sats = [sat for pair in Faultysats for sat, epoch in pair.iteritems()
if sat in SATS and epoch == EPOCH]
>>> sats
['G11']
Now you can use a dictionary comprehension to provide the index location of each satellite in SATS (assuming there are no duplicates).
>>> {s: SATS.index(s) for s in sats}
{'G11': 4}
This question already has answers here:
Euler project #18 approach
(10 answers)
Closed 9 years ago.
I'm trying to solve project euler problem 18/67 . I have an attempt but it isn't correct.
tri = '''\
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23'''
sum = 0
spot_index = 0
triarr = list(filter(lambda e: len(e) > 0, [[int(nm) for nm in ln.split()] for ln in tri.split('\n')]))
for i in triarr:
if len(i) == 1:
sum += i[0]
elif len(i) == 2:
spot_index = i.index(max(i))
sum += i[spot_index]
else:
spot_index = i.index(max(i[spot_index],i[spot_index+1]))
sum += i[spot_index]
print(sum)
When I run the program, it is always a little bit off of what the correct sum/output should be. I'm pretty sure that it's an algorithm problem, but I don't know how exactly to fix it or what the best approach to the original problem might be.
Your algorithm is wrong. Consider if there was a large number like 1000000 on the bottom row. Your algorithm might follow a path that doesn't find it at all.
The question hints that this one can be brute forced, but that there is also a more clever way to solve it.
Somehow your algorithm will need to consider all possible pathways/sums.
The brute force method is to try each and every one from top to bottom.
The clever way uses a technique called dynamic programming
Here's the algorithm. I'll let you figure out a way to code it.
Start with the two bottom rows. At each element of the next-to-bottom row, figure out what the sum will be if you reach that element by adding the maximum of the two elements of the bottom row that correspond to the current element of the next-to-bottom row. For instance, given the sample above, the left-most element of the next-to-bottom row is 63, and if you ever reach that element, you will certainly choose its right child 62. So you can replace the 63 on the next-to-bottom row with 63 + 62 = 125. Do the same for each element of the next-to-bottom row; you will get 125, 164, 102, 95, 112, 123, 165, 128, 166, 109, 112, 147, 100, 54. Now delete the bottom row and repeat on the reduced triangle.
There is also a top-down algorithm that is dual to the one given above. I'll let you figure that out, too.