I am trying to create a nested list using the lines of a .txt file, but can't reach my desired form.
.txt file content:
[1,2,3]
[2,3,4]
[3,4,5]
Code:
nested_List = []
file = open("example_File.txt",'r')
for i in file:
element = i.rstrip("\n")
nested_List.append(element)
arch.close()
return (esta)
The result I get:
['[1,2,3]', '[2,3,4]', '[3,4,5]']
What I want:
[[1,2,3],[2,3,4],[3,4,5]]
You need to convert the string representing the list to an actual list. You can use ast.literal_eval like:
from ast import literal_eval
nested_list = []
with open("file1", 'r') as f:
for i in f:
nested_list.append(literal_eval(i))
print(nested_list)
Or with a list comprehension like:
with open("file1", 'r') as f:
nested_list = [literal_eval(line) for line in f]
print(nested_list)
Results:
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
I was thinking something similar and came up with the following which uses the python's abstract syntax tree's literal_eval function.
import ast
nested_List = []
with open("example_File.txt", 'r') as infile:
for i in infile:
element = i.rstrip("\n")
nested_List.append(ast.literal_eval(element))
print(nested_List)
Related
I want to save a list in .csv. I had syntax, but it save in rows instead of columns. Please give suggestion. Thanks in advance.
My syntax is:
import csv
n=0
x=[]
while n < 10:
n = n+1
x.append(n)
with open('test.csv','w') as file:
writer = csv.writer(file)
writer.writerows([x])
print(x)
The way writerows functions is that it takes an iterable (in this case, a list) and prints each item on that iterable on its own line, separated by delimiter (by default, a ,)
What happens here is that you're passing [[1,2,3,4,5,6,7,8,9,10]] which means there is a single row ([1,2,3,4,5,6,7,8,9,10]) to be written out.
If you want to write each item to it's own row, you need to provide each item as its own list:
import csv
n = 0
x = []
while n < 10:
n = n+1
x.append([n])
print(x)
with open('test.csv', 'w') as file:
writer = csv.writer(file)
writer.writerows(x)
Here, I've taken out the [] around x in the last line and moved them into x.append([n]) to create x that is [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
Have you tried replacing the writerows line by:
writer.writerows(np.array([x]).T)
It should work. (you should import numpy as np, of course)
You need to pass the csv.writerows() method an "an iterable of row objects", which can be a generator expression. Also note you should open csv files with newline='' in Python 3.x as shown in the module's documentation.
Here's how to do it. Note how each value in the list is (temporarily) turned into a list of one item by the [v] part of the expression.
import csv
x = list(range(10))
with open('testfile.csv', 'w', newline='') as file:
csv.writer(file).writerows(([v] for v in x))
print('done')
I have the below list of lists
[['Afghanistan,2.66171813,7.460143566,0.490880072,52.33952713,0.427010864,-0.106340349,0.261178523'], ['Albania,4.639548302,9.373718262,0.637698293,69.05165863,0.74961102,-0.035140377,0.457737535']]
I want to create a new list with only the country names.
So
[Afghanistan, Albania]
Currently using this code.
with open(fileName, "r") as f:
_= next(f)
row_lst = f.read().split()
countryLst = [[i] for i in row_lst]
Try this, using split(',') as your first element in list of list is string separated by comma.
>>> lst = [['Afghanistan,2.66171813,7.460143566,0.490880072,52.33952713,0.427010864,-0.106340349,0.261178523'], ['Albania,4.639548302,9.373718262,0.637698293,69.05165863,0.74961102,-0.035140377,0.457737535']]
Output:
>>> [el[0].split(',')[0] for el in lst]
['Afghanistan', 'Albania']
Explanation:
# el[0] gives the first element in you list which a string.
# .split(',') returns a list of elements after spliting by `,`
# [0] finally selecting your first element as required.
Edit-1:
Using regex,
pattern = r'([a-zA-Z]+)'
new_lst = []
for el in lst:
new_lst+=re.findall(pattern, el[0])
>>> new_lst # output
['Afghanistan', 'Albania']
Looks like a CSV file. Use the csv module
Ex:
import csv
with open(fileName, "r") as f:
reader = csv.reader(f)
next(reader) #Skip header
country = [row[0] for row in reader]
I have two lists with variable lengths
list1 = ['x1','x2','x3','x4','x5']
list2 = ['x5','x4']
I try the following to find the missing elements
*[item for item in list1 if item not in list2], sep='\n'
but if I do
item = *[item for item in skuslist if item not in retaillist], sep='\n'
csvwriter.writerow(item)
I get can't assign to list comprehension
How can I pass the results to writerow?
You can try like this:
import csv
list1 = ['x1','x2','x3','x4','x5']
list2 = ['x5','x4']
with open('output.csv', 'w') as f:
writer = csv.writer(f, delimiter='\n', quoting=csv.QUOTE_NONE)
writer.writerow([item for item in list1 if item not in list2])
You need to use writerows to write one item per line, and put each item in a 1-element list:
list1 = ['x1','x2','x3','x4','x5']
list2 = {'x5','x4'}
import csv
with open("test.csv","w",newline="") as f:
cw = csv.writer(f)
cw.writerows([x] for x in list1 if x not in list2)
Detail: create a set for values to exclude, as lookup is faster (that is, for more elements)
Here is another way to accomplish this task. This method create a set based on the differences between list1 and list2. The code also writes the values to the CSV file in order.
import csv
list1 = ['x1','x2','x3','x4','x5']
list2 = ['x5','x4']
# Obtain the differences between list1 and list2
list_difference = (list(set(list1).difference(list2)))
# Uses list comprehension to write the values to a CSV file.
# Uses sorted to write the values in order to the CSV file.
with open('output.csv', 'w') as outfile:
csv_writer = csv.writer(outfile)
csv_writer.writerows([[x] for x in sorted(list_difference)])
outfile.close()
You can also do it this way.
import csv
list1 = ['x1','x2','x3','x4','x5']
list2 = ['x5','x4']
# Obtain the differences between list1 and list2.
# Uses list comprehension to write the values to a CSV file.
# Uses sorted to write the values in order to the CSV file.
with open('output.csv', 'w') as outfile:
csv_writer = csv.writer(outfile)
csv_writer.writerows([[x] for x in sorted(list(set(list1).difference(list2)))])
outfile.close()
I've got a text file like this:
1;2;3;4
5;6;7;8
And I'd like to transform it to:
[[1,2,3,4],[5,6,7,8]]
Using Python, how can i achieve this?*
You can use the following:
data = [[int(i) for i in line.split(';')] for line in open(filename)]
Alternative using the csv module:
import csv
data = [[int(i) for i in ln] for ln in csv.reader(open(filename), delimiter=';')]
If lists of strings are acceptable:
data = [line.split(';') for line in open(filename)]
Or the csv equivalent:
data = list(csv.reader(open(filename), delimiter=';'))
As a multi-line string:
>>> s = """1;2;3;4
5;6;7;8"""
>>> [[int(x) for x in a.split(';')] for a in s.splitlines()]
[[1, 2, 3, 4], [5, 6, 7, 8]]
As your data seems to be some sort of CSV like data, why not use python's csv parsing module? This handles encoding and supports delimiters all for free.
If you just want some code, use a list comprehension and split using the split method of str:
result = [line.split(';') for line in text.split("\n")]
'1;2;3;4'.split(';') will produce the list [1, 2, 3, 4] from the string '1;2;3;4', so you just need to do that for each line in your file:
def split_lists(filepath, sep=';'):
with open(filepath) as f:
line_lists = []
for line in f:
line_lists.append(line.split(sep))
return line_lists
Or more compactly with a comprehension
def split_lists(filepath, sep=';'):
with open(filepath) as f:
return [line.split(sep) for line in f]
thanks for the interesting question, can be resolved by 2 map and one for loop
s='1;2;3;4\n5;6;7;8'
map(lambda seq: [int(i) for i in seq], map(lambda x:x.split(';'), s.split('\n')))
I have a piece of code that loads up 2 lists with this code:
with open('blacklists.bls', 'r') as f:
L = [dnsbls.strip() for dnsbls in f]
with open('ignore.bls', 'r') as f2:
L2 = [ignbls.stip() for ignbls in f2]
dnsbls contains:
list1
list2
list3
ignbls contains
list2
What I want to do is merge dnsbls and ignbls and then remove any lines that appears more than once and print those with "for". I was thinking something like:
for combinedlist in L3:
print combinedlist
Which in the aboe example would print out:
list1
list3
You need to use sets instead of lists:
L3 = list(set(L).difference(L2))
Demonstration:
>>> L=['list1','list2','list3']
>>> L2=['list2']
>>> set(L).difference(L2)
set(['list1', 'list3'])
>>> list(set(L).difference(L2))
['list1', 'list3']
For your purposes you probably don't have to convert it back to a list again, you can iterate over the resulting set just fine.
If ignores are smaller than the blacklists (which is normally the case I think), then (untested):
with open('blacklists.bls') as bl, open('ignore.bls') as ig:
bl_for = (line.strip() for line in bl if 'for' not in line)
ig_for = (line.strip() for line in ig if 'for' not in line)
res = set(ig_for).difference(bl_for)