简体   繁体   中英

Identify common string in a list using Python

If I have a list as so:

"a1, a2, a3, b1, b2, b3"

Is it possible to use Python to detect the common characters and tell me what they are and how many of each? Another words, I want the code to scan the list for commonalities and tell me there are 3 strings starting with 'a', and 3 starting with 'b'...

The ultimate goal is to be able to identify a user's naming system from a list of file names. I know how to create the list of file names from the directory and they should all have some system to their naming, eg Subject1_Image1, Subject1_Image2, Subject2_Image1, Subject2_Image2... but I have no way of knowing what that system will be as it's up to the user. Need Python to identify their naming system and rename files according to "my" system as that naming pattern is later used in code in R.

The purpose for this is that I'm writing an automated imaged analysis application where statistical analysis is being performed in R, and R needs to call for specific files to get quantitative info for processing, so I need the naming system to be "mine" rather than the user's (and I don't want to make the user rename everything themselves to my system).

Hope my question makes sense?

TIA

Using a for loop:

names = ['a1', 'a2', 'b0', 'b3', 'bb4', 'c0ugh']

counts = dict()
for name in names:
   if name[0] in counts.keys():
      counts[name[0]] += 1
   else:
      counts[name[0]] = 1

print(counts)
# {'a': 2, 'b': 3, 'c':1}

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