2016-05-08 6 views
0

私はリストを取って、それ以外のすべての要素を分けて、リストの順序を変えずにこのプログラムを実行しようとしています。 例えば、
[1,2,3,1,3] = [1,3,1,3]
[5,5,5,5] = [5,5,5,5]
[1,2 、3,4,5] = []"for"ループでリストをリセット

したがって、このために、私はPythonでプログラムを行なったし、私はLIST3値をリセットしようとしたプログラムでwrong.Soをやっているところに私が知っている助けるためにいくつかのフラグを入れます(ループの中の要素を削除して終了した後)、それは私にそれをさせてくれませんでした。だから、どんな助けも大歓迎です。皆さんありがとう。

list1=[1,2,3,1,3] 
list2=[] 
d=0 
m=0 
l=len(list1) 
print(l) 
for x in range(0,l): 
    print('for loop') 
    list3=list1 # I used this to reset the list3 to list1 and use it in the loop but it wouldn't reset 
    print('this is the reset of list 3',list3) 
    m=list1[x] 
    print(m,x) 
    print(list3[x]) 
    del (list3[x]) 

    while True: 
     print('while loop',list3[d]) 

     if m==list3[d]: 
      print('its here') 
      list2.append(m) 
      print('this is list2: ',list2) 
     d+=1 

     if d==lenght(list3)-1: 
      print('its here22222') 
      break 
print(list2) 

# my results were 

5 
for loop 
this is the reset of list 3 [1, 2, 3, 1, 3] 
1 0 
1 
while loop 2 
while loop 3 
while loop 1 
its here 
this is list2: [1] 
its here22222 
for loop 
this is the reset of list 3 [2, 3, 1, 3] 
3 1 
IndexError: list index out of range 
+1

LIST3 =リスト1リスト1をコピーされていない、http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-pythonを参照してください – paisanco

答えて

0

これでいいですか?

#list1=[5,5,5,5,5] 
list1=[1,2,3,1,3] 
#list1=[1,2,3,4,5] 
list2=[] 

for num in list1: 
    if list1.count(num) > 1: 
     list2.append(num) 

print(list2) 
+0

それは作業を行います。私はカウント関数を知っています。私もそれを使用しました。 9行目のlist3がlist3をlist1にリセットしない理由は分かりません。ありがとう@ dovo36。 :) – vineeth

+0

ああ、大丈夫です。それは上のpaisoncoが言ったとおりです。 list3 = list1 list3はlist1と同じメモリを指し示します。だから、彼らは同じものの2つの異なるラベルです。 list1をコピーしてlist3を上書きし、彼が与えたリンクを読むと、それは実行できるさまざまな方法が示されます。 – davo36

+0

ありがとう@ davo36。本当に私を助けてくれた – vineeth

関連する問題