inserting a value in a 2d list - python 2.7 - list

i have a list....
lst = [[45], [78], [264], [74], [67], [4756], [455], [465], [4567], [4566]]
and i want to add a zero at the beginning so it looks like this....
lst = [[0], [45], [78], [264], [74], [67], [4756], [455], [465], [4567], [4566]]
This doesn't work...
lst[0] = [0]
or This...
lst.append(0,[0])
what will actually work?
cheers

As the name goes, append always adds at the end. You need to do this:
lst.insert(0, [0])
in stead of lst.append(0,[0])

Related

How to turn this list of lists into a dictionary where the first item of each sublist is used as key? [duplicate]

This question already has answers here:
Get first element of sublist as dictionary key in python
(5 answers)
Closed 3 months ago.
The original list is:
[['James', '100.00', '90.00', '85.50'], ['Nick', '78.00', '85.00', '80.50'], ['William', '95.50', '92.00', '100.00']]
I want to turn the list into a dictionary that look like this:
{'James': ['100.00', '90.00', '85.50'], 'Nick': ['78.00', '85.00', '80.50'], 'William': ['95.50', '92.00', '100.00']}
Could anyone please tell me how to get the output for this?
d = {}
for sublist in orig_list:
new_key, new_value = sublist[0], sublist[1:]
d[new_key] = new_value
Since you're a beginner, it's best to take a beginner's approach...
You want a dictionary, so you start by creating an empty one.
Then we'll iterate over the list you've been given, and for each sublist of the list, we'll take the first element and make it a new key in the dictionary. And we'll take the remaining elements of the list and make them a new value of the new key.
When you're done processing, you'll have the dict that you want.
Since others mention a "dictionary comprehension," I'll add that to my answer, as well. A dict comp. that corresponds to what I've done above could be:
d = {sublist[0]: sublist[1:] for sublist in orig_list}
But, as I've mentioned below in my comments, I don't think a dictionary comprehension is appropriate for a beginner programmer. My first solution is the better one.
We can use a dictionary comprehension:
inp = [['James', '100.00', '90.00', '85.50'], ['Nick', '78.00', '85.00', '80.50'], ['William', '95.50', '92.00', '100.00']]
d = {x[0]: x[1:4] for x in inp}
print(d)
This prints:
{'James': ['100.00', '90.00', '85.50'],
'Nick': ['78.00', '85.00', '80.50'],
'William': ['95.50', '92.00', '100.00']}
Maybe you can try this following code :
list1 = [
['James', '100.00', '90.00', '85.50'],
['Nick', '78.00', '85.00', '80.50'],
['William', '95.50', '92.00', '100.00']
]
list1_to_dict = dict((x[0], x[1:]) for x in list1)
print(list1_to_dict)
Hope it will help you :)

Python keeps printing first index of for loop

I have data in two directories and i'm using for loop to read the files from both the folders.
path_to_files = '/home/Desktop/computed_2d/'
path_to_files1 = '/home/Desktop/computed_1d/'
for filen in [x for x in os.listdir(path_to_files) if '.ares' in x]:
df = pd.read_table(path_to_files+filen, skiprows=0, usecols=(0,1,2,3,4,8),names=['wave','num','stlines','fwhm','EWs','MeasredWave'],delimiter=r'\s+')
for filen1 in [x for x in os.listdir(path_to_files1) if '.ares' in x]:
df1 = pd.read_table(path_to_files1+filen1, skiprows=0, usecols=(0,1,2,3,4,8),names=['wave','num','stlines','fwhm','EWs','MeasredWave'],delimiter=r'\s+')
print(filen,filen1)
Now what's happening is like when tried to print the filenames then it kept printing the names forever. So, its basically taking the first iteration from first loop then print it with all the iteration of the second loop.I don't understand why is it happening.
But what i want to do is, i want to print the first iteration of first loop with the first iteration of second for loop
As the file names are same in both the folders.So when i do the print, then desired result should look like something like this:
(txt_1.txt,txt_1.txt)
(txt_2.txt,txt_2.txt)
(txt_3.txt,txt_3.txt)
(txt_4.txt,txt_4.txt)
Where i'm making the mistake??
If I understand your question correctly, you seem to want to print pairs of files from path_to_files and path_to_files1. Since you are nesting a for loop, for every iteration of the nested for loop, filen is not going to change.
I think you might want something more like this:
path_to_files = '/home/Desktop/computed_2d/'
path_to_files1 = '/home/Desktop/computed_1d/'
filelistn = [x for x in os.listdir(path_to_files) if '.ares' in x]
filelist1 = [x for x in os.listdir(path_to_files1) if '.ares' in x]
for filen, filen1 in zip(filelistn, filelist1):
df = pd.read_table(path_to_files+filen, skiprows=0, usecols=(0,1,2,3,4,8),names=['wave','num','stlines','fwhm','EWs','MeasredWave'],delimiter=r'\s+')
df1 = pd.read_table(path_to_files1+filen1, skiprows=0, usecols=(0,1,2,3,4,8),names=['wave','num','stlines','fwhm','EWs','MeasredWave'],delimiter=r'\s+')
print(filen,filen1)
For a sample input of:
filelistn = ['a.ar', 'b.ar']
filelist1 = ['c.ar', 'd.ar']
I get the following output:
('a.ar', 'c.ar')
('b.ar', 'd.ar')

Scala: how to flatten a List of a Set of filepaths

I have a List[Set[Path]]: Update: Each Path in a Set is unique and represents a particular directory location. There are no duplicates. So, what I am looking for is the total number of path elements/
val miceData = List(Set(C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test7.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test2.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test6.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test5.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test8.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test3.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\aPowerPoint.pptx, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test1.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test4.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test10.txt), Set(C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test6.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test3.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test4.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test70.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test8.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test5.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test2.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test2.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test3.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test1.txt), Set(C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test80.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test7.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test40.txt, C:\Users\lulu\Documents\GitHub\data_mining_folder\FlatDirectory\Test6.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test5.txt), Set(C:\Users\lulu\Documents\mice_data\data_mining_folder\zipfile.zip), Set(C:\Users\lulu\Documents\mice_data\data_mining_folder\micetest.txt,C:\Users\lulu\Documents\mice_data\data_mining_folder\riley.jpg))
There are 5 Sets in this List, each Set holding Path(s). The total number of such Paths is 28, if I counted correctly.
Now, I want to find out the total number of Path elements across all Sets in this List.
I could have done this computation in an area of my code upstream, but I am curious to do so now, and learn more about Scala in the process.
Something like:
val totalPaths = <<iterate over this List and count all the paths>>
I would like the shortest, most idiomatic piece of code to accomplish this.
val paths = for { //gives you a list of all paths on all sets
set <- miceData
path <- set
} yield path
val totalPaths = paths.toSet.size // converting it to set will remove duplicates if any
I think flatten is just enough
val toto = List(Set(1,2,3), Set(6,7,8))
println(toto.flatten.count)
val totalPaths = miceData.map(_.size).sum
If you have duplicates, you can do :
val totalPaths = miceData.flatten.distinct.size
val totalPaths = miceData.flatten.size
OR
val totalPaths = miceData.flatten.length
And you might want to give your paths as triple qouted Strings. because with single quotes REPL is giving the following error.
<console>:1: error: invalid escape character
List(Set("C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test7.txt", "C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test2.txt")).flatten.size

Getting duplicates in dict

I have a dictionary, say d1 that looks like this:
d = {'file1': 4098, 'file2': 4139, 'file3': 4098, 'file4': 1353, 'file5': 4139}
Now, I've figured out how to get it to tell me if there are any dublicates or not. But what I'd like to get it to do is tell me if there are any, and what 2 (or more) values (and corresponding keys) are dublicates.
The output for the above would tell me that file1 and file3 are identical and that file2 and file5 are identical
I've been trying to wrap my head around it for a few hours, and haven't found the right solution yet.
try this to get the duplicates:
[item for item in d.items() if [val for val in d.values()].count(item[1]) > 1]
that outputs:
[('file3', 4098), ('file2', 4139), ('file1', 4098), ('file5', 4139)]
next sort the list by the second item in the tuple:
list = sorted(list, key=operator.itemgetter(1))
finally use itertools.groupby() to group by the second item:
list = [list(group) for key, group in itertools.groupby(list, operator.itemgetter(1))]
final output:
[[('file3', 4098), ('file1', 4098)], [('file2', 4139), ('file5', 4139)]]

Erlang: List Comprehension to an Existing List

I am trying to create a new list via a list comprehension but want those new values to be included in an existing list.
More specifically, I am try to create a string out of the date and will have some string formatting between the values ( a dash - ). The existing list will be a template if you will with the dash.
Here is what I have so far:
{Date, Time} = erlang:universaltime().
DateList = tuple_to_list(Date).
DateListString = [ integer_to_list(X) || X < DateList ].
DateListStringConcatenate = lists:flatten(DateListString).
The result should be something along
"20101121"
But, what I want is
"2010-11-21"
So I am thinking about the DateListString comprehension "comprehending" to an existing list with "-" after the first and second element.
Any suggestions accompanied with concrete code samples much appreciated.
1> {{Y,M,D},_} = erlang:universaltime().
{{2010,11,21},{16,42,56}}
2> lists:flatten(io_lib:format("~p-~p-~p", [Y,M,D])).
"2010-11-21"
If you really want it in a list comprehension then you could do the following:
{Date, Time} = erlang:universaltime().
DateList = tuple_to_list(Date).
DateListString = [ [$- | integer_to_list(X)] || X <- DateList ].
[_ | DateListStringConcatenate] = lists:flatten(DateListString).
Roberto's is a better/more efficient solution to this but in case you wondered how you might do it with a list comprehension this would be one way.
This is a possible solution, but I feel that it is not an elegant one. Also, it does not use list comprehension.
1> {Date, Time} = erlang:universaltime().
{{2010,11,21},{14,51,23}}
2> DateList = tuple_to_list(Date).
[2010,11,21]
3> DateListString = lists:zipwith(fun(X,Y) -> integer_to_list(X) ++ Y end, DateList, ["-","-",""]).
["2010-","11-","21"]
4> DateListStringConcatenate = lists:flatten(DateListString).
"2010-11-21"