简体   繁体   中英

1-liner for loop in python

I have this 1-liner:

python -c 'import json,sys;obj=json.load(sys.stdin);print json.dumps(obj.get("dependencies"), indent=0, sort_keys=True)' < package.json

And I would like to find a nice, short solution instead of repeating myself, to do the print looping over ["dependencies", "devDependencies", "peerDependencies"] .

The trivial, but not nice solution I have now:

python -c 'import json,sys;obj=json.load(sys.stdin);print json.dumps(obj.get("dependencies"), indent=0, sort_keys=True);print json.dumps(obj.get("devDependencies"), indent=0, sort_keys=True);print json.dumps(obj.get("peerDependencies"), indent=0, sort_keys=True)' < package.json

I also tried things similar to:

python -c 'import json,sys;obj=json.load(sys.stdin);[print json.dumps(obj.get(dep), indent=0, sort_keys=True) for dep in "dependencies","devDependencies","peerDependencies"]' < package.json

UPDATE:

My goal is to get all the dependencies that have "git" in their url:

Input: package.json:

{
  "foo": "bar",
  "dependencies": {
    "a": "git:aa",
    "b": "git:bb",
    "c": "cc"
  },
  "peerDependencies": {
    "p": "git:pp"
  },
  "devDependencies": {
    "d": "git:dd"
  },
  "moo": "poo"
}

Expected output:

{
"a": "git:aa",
"b": "git:bb",
"c": "cc"
} {
"p": "git:pp"
} {
"d": "git:dd"
}

In fact I don't care much about the "}"-s and "{"-s, because I'll continue the 1-liner with: | grep 'git:' | grep 'git:'

you are looking for join :

import json,sys
obj=json.load(sys.stdin)
print ' '.join(json.dumps(obj.get(dep), indent=0, sort_keys=True) for dep in ("dependencies", "devDependencies", "peerDependencies"))

That's not a 1-liner, that's just you making your life harder. Your 1-liner can be as simple as:

python my-script.py

And have a nice formatted code inside a text file that doesn't goes against the entire spirit of the language: https://www.python.org/dev/peps/pep-0008/

Now about your problem:

import json, sys

deps = ["dependencies", "peerDependencies", "devDependencies"]
data = json.loads(sys.stdin)

for dep in deps:
    if data[dep].startswith("git:"):
        print data[dep]

I think that should do it, and then you don't need to | grep | grep the output. Note that this is filtering dependencies that START with git: , NOT the ones that CONTAINS it as you requested, because i figured out that's what you want. Otherwise, you can replace the if data[dep].startswith("git:") by if "git:" in data[dep] and that would do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM