Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
in Technique[技术] by (71.8m points)

python - Comparing lists and strings

So I've got a string called "correct_body", which is either: "Large narrow body,,£7,5600,220,10" or "Medium wide body,,£5,4050,406,14" or "Medium narrow body,,£8,2650,180,8. And I've got a list called, "max_distance" containing these numbers: ['5600', '4050', '2650'] I want to be able to compare the list with the string and if one of the list's number is in the string I'd like it to be printed. Here's my code:

for x in max_distance:
        if x in correct_body:
            distance = x
            print(distance)

So if the string is "Large narrow body,,£7,5600,220,10" then 5600 should be printed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could extract the digits from the string using a pattern to match £d+, and capture the following digits in a capture group (d+).

If there is a match, re.findall will return the value(s) from the capture group and you can check if the list contains the value(s).

import re

correct_body = re.findall(r"£d+,(d+)", "Large narrow body,,£7,5600,220,10")
max_distance = ['5600', '4050', '2650']

for x in max_distance:
    if x in correct_body:
        distance = x
        print(distance)

Output

5600

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...