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
174 views
in Technique[技术] by (71.8m points)

python - Append on condition

I'm going to write a program that takes some lines and translates them into one line but unfortunately, I have a problem with appending uncommon elements. this is what I've done so far:

List_of_sentences = []
for line in range(int(input())):
    List_of_sentences.append(input().strip().split())

Sample_sentence = input().split()

Final_list = []

for lists in List_of_sentences:
    for elements in Sample_sentence:
        if elements in lists:
            Final_list.append(lists[0])
        else:
            Final_list.append(elements)
            
print(' '.join(Final_list))

for example, consider these two lists:

List_of_sentences = [['man', 'I', 'je', 'ich'], ['kheili', 'very', 'très', 'sehr'], ['alaghemand', 'interested', 'intéressé', 'interessiert'], ['barnamenevisi', 'programming', 'laprogrammation', 'Programmierung']]

Sample_sentence = ['I', 'am', 'very', 'interested', 'in', 'programming']

it has to return this:

man am kheili alaghemand in barnamenevisi

but instead:

man kheili alaghemand barnamenevisi

my problem is with else part

any help is highly appreciated

question from:https://stackoverflow.com/questions/65847866/append-on-condition

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

1 Reply

0 votes
by (71.8m points)

Your loop seems little bit messed up. It should be like this order

List_of_sentences = []
for line in range(int(input())):
    List_of_sentences.append(input().strip().split())

Sample_sentence = input().split()

Final_list = []

for elements in Sample_sentence: #this for loop should be first
    var = None
    for lists in List_of_sentences: # this for loop should be second
        if elements in lists:
            #Final_list.append(lists[0])
            var = lists[0]
            break
    Final_list.append(var if var else elements)
            
print(' '.join(Final_list))

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

...