Asked  7 Months ago    Answers:  5   Viewed   29 times

I have a list of strings such as:

names = ['apple','orange','banana'] 

And I would like to create a list for each element in the list, that would be named exactly as the string:

apple = []  
orange = []  
banana = []  

How can I do that in Python?

 Answers

69

You would do this by creating a dict:

fruits = {k:[] for k in names}

Then access each by (for eg:) fruits['apple'] - you do not want to go down the road of separate variables!

Tuesday, June 1, 2021
 
leebriggs
answered 7 Months ago
27

python3 is not Python syntax, it is the Python binary itself, the thing you run to get to the interactive interpreter.

You are confusing the command line with the Python prompt. Open a console (Windows) or terminal (Linux, Mac), the same place you'd use dir or ls to explore your filesystem from the command line.

If you are typing at a >>> or In [number]: prompt you are in the wrong place, that's the Python interpreter itself and it only takes Python syntax. If you started the Python prompt from a command line, exit at this point and go back to the command line. If you started the interpreter from IDLE or in an IDE, then you need to open a terminal or console as a separate program.

Other programs that people often confuse for Python syntax; each of these is actually a program to run in your command prompt:

  • python, python2.7, python3.5, etc.
  • pip or pip3
  • virtualenv
  • ipython
  • easy_install
  • django-admin
  • conda
  • flask
  • scrapy
  • setup.py -- this is a script you need to run with python setup.py [...].
  • Any of the above together with sudo.

with many more variations possible depending on what tools and libraries you have installed and what you are trying to do.

If given arguments, you'll get a SyntaxError exception instead, but the underlying cause is the same:

>>> pip install foobar
  File "<stdin>", line 1
    pip install foobar
              ^
SyntaxError: invalid syntax
Tuesday, June 1, 2021
 
QuantumMechanic
answered 7 Months ago
92

This is a little more flexible than Satoru's, and doesn't use any libraries. Still, it won't work with more deeply nested lists. For that, I think you would need a recursive function (or loop), or eval.

str = "[[0,0,0],[0,0,1],[1,1,0]]"
strs = str.replace('[','').split('],')
lists = [map(int, s.replace(']','').split(',')) for s in strs]

lists now contains the list of lists you want.

Tuesday, July 6, 2021
 
ioleo
answered 5 Months ago
10
  • startswith and in, return a Boolean
  • The in operator is a test of membership.
  • This can be performed with a list-comprehension or filter
  • Using a list-comprehension, with in, is the fastest implementation tested.
  • If case is not an issue, consider mapping all the words to lowercase.
    • l = list(map(str.lower, l)).

filter:

  • Using filter creates a filter object, so list() is used to show all the matching values in a list.
l = ['ones', 'twos', 'threes']
wanted = 'three'

# using startswith
result = list(filter(lambda x: x.startswith(wanted), l))

# using in
result = list(filter(lambda x: wanted in x, l))

print(result)
[out]:
['threes']

list-comprehension

l = ['ones', 'twos', 'threes']
wanted = 'three'

# using startswith
result = [v for v in l if v.startswith(wanted)]

# using in
result = [v for v in l if wanted in v]

print(result)
[out]:
['threes']

Which implementation is faster?

  • Using the words corpus from nltk
  • Words with 'three'
    • ['three', 'threefold', 'threefolded', 'threefoldedness', 'threefoldly', 'threefoldness', 'threeling', 'threeness', 'threepence', 'threepenny', 'threepennyworth', 'threescore', 'threesome']
from nltk.corpus import words

%timeit list(filter(lambda x: x.startswith(wanted), words.words()))
[out]:
47.4 ms ± 1.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit list(filter(lambda x: wanted in x, words.words()))
[out]:
27 ms ± 1.78 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit [v for v in words.words() if v.startswith(wanted)]
[out]:
34.1 ms ± 768 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit [v for v in words.words() if wanted in v]
[out]:
14.5 ms ± 63.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Tuesday, August 10, 2021
 
Evan
answered 4 Months ago
58

use the following to convert to a timestamp in python 2

int((mod_time.mktime(first_run.timetuple())+first_run.microsecond/1000000.0))

Sunday, August 22, 2021
 
waylaidwanderer
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share