简体   繁体   中英

What is the most pythonic way to extract branch names from a remote-ls list?

I'm an experienced coder that's new to Python.

I have a branch list fetched with the git ls-remote command :

db6ad7246abf74cb845baa60e6fe45dacf897612    HEAD
1fc347b17201054d8b5b9593efc1925918f04940    refs/heads/develop
63b1a5b5901250651a162814b085c88c96835e3a    refs/heads/feature-dm
8d72969f3b1ef5b16792b1cca5c65262d78b8dc2    refs/heads/feature/breedtest
0ca9346d1f5b46f77f41a89aeb11998cbb83c007    refs/heads/feature/fedortest
147bea618187c11927bfe83f1d8b52591f3b734c    refs/heads/feature/frontend-autumn14
d5e5d4d75dddd46a5068ca621ce8e74e68bdca4e    refs/heads/feature/socket-testing
03e70c846a84688ccbf78ca1159f410e577e1ee5    refs/heads/feature/youtracktest
db6ad7246abf74cb845baa60e6fe45dacf897612    refs/heads/master
787580497c0b41ca040c60bd7906ab598f891a43    refs/heads/master-old
33a553135eb4341046702adaa762791b38456daf    refs/pull/67/head
10c4c172ba0479dac8eefba674395d09d9d4b061    refs/pull/67/merge

I want to extract only the branch names from refs/heads/ :

develop
feature-dm
feature/breedtest
feature/fedortest
feature/frontend-autumn14
feature/socket-testing
feature/youtracktest
master
master-old

I can split on a new line and use regexp - but I'm sure there is probably a smart pythonic way to do this...

Once you split on new lines and have a list of strings.

l = ['db6ad7246abf74cb845baa60e6fe45dacf897612    HEAD',
     '1fc347b17201054d8b5b9593efc1925918f04940    refs/heads/develop',
     '63b1a5b5901250651a162814b085c88c96835e3a    refs/heads/feature-dm',
     '8d72969f3b1ef5b16792b1cca5c65262d78b8dc2    refs/heads/feature/breedtest',
     '0ca9346d1f5b46f77f41a89aeb11998cbb83c007    refs/heads/feature/fedortest',
     '147bea618187c11927bfe83f1d8b52591f3b734c    refs/heads/feature/frontend-autumn14',
     'd5e5d4d75dddd46a5068ca621ce8e74e68bdca4e    refs/heads/feature/socket-testing',
     '03e70c846a84688ccbf78ca1159f410e577e1ee5    refs/heads/feature/youtracktest',
     'db6ad7246abf74cb845baa60e6fe45dacf897612    refs/heads/master',
     '787580497c0b41ca040c60bd7906ab598f891a43    refs/heads/master-old',
     '33a553135eb4341046702adaa762791b38456daf    refs/pull/67/head',
     '10c4c172ba0479dac8eefba674395d09d9d4b061    refs/pull/67/merge']

You can use a list comprehension.

s = 'refs/heads/'
[i.split()[1][len(s):] for i in l if s in i]

Output

['develop',
 'feature-dm',
 'feature/breedtest',
 'feature/fedortest',
 'feature/frontend-autumn14',
 'feature/socket-testing',
 'feature/youtracktest',
 'master',
 'master-old']

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