列出if-else没有给出预期结果

时间:2019-03-04 04:44:38

标签: python list sorting if-statement

我有以下列表列表:

[['3', 2], ['2370447', 282], ['5300058', 610], ['81615', 615], ['3294332', 624], ['3078798', 624], ['1804986', 643]]

请注意,索引5和6中的第二项相同。我试图将每个列表中第二个项目上排序的列表转换为排名。

当值相同时,我使用以下if-else来校正时间:

for i in range(len(sortedCounts)):
   if i == 0:
          sortedCounts[i][1] = 0
   elif sortedCounts[i][1] == sortedCounts[i-1][1]:
          sortedCounts[i][1] = i-1
   else: 
          sortedCounts[i][1] = i

但是,当我打印列表时,即使数字相同,我也会得到不同的排名:

[['3', 0], ['2370447', 1], ['5300058', 2], ['81615', 3], ['3294332', 4], ['3078798', 5], ['1804986', 6]]

预期输出为:

[['3', 0], ['2370447', 1], ['5300058', 2], ['81615', 3], ['3294332', 4], ['3078798', 4], ['1804986', 6]]

赞赏任何建议,或者如果有更好的方法,请提出建议。

5 个答案:

答案 0 :(得分:1)

rank, last_value = -1, -1
for i, e in enumerate(sortedCount):
    if last_value < e[1]:
        rank = i
    last_value = e[1]
    sortedCount[i][1] = rank

答案 1 :(得分:1)

我认为这是您期望的代码

public class test extends AppCompatActivity {

//Database
private String userID;
//private Button buttonAdd;

private static final String TAG = "ViewDatabase";
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
public String personId;
//private DatabaseReference mHeadingReference = mRootReference.child("users");
public DataSnapshot dataSnapshot;
public HashMap<String,String> map = new HashMap<String,String>();
public String prints;
public String e;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);


    mAuth = FirebaseAuth.getInstance();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference();
    FirebaseUser user = mAuth.getCurrentUser();
    userID = user.getUid();
    Gson json = new Gson();
    map.put("password","www.google.com");
    String hashMapString = json.toJson(map);
    myRef.child(userID).setValue(hashMapString);

    Log.d("STATE", "onCreate: "+ myRef.child(userID));
    String print = myRef.child(userID).getKey();//prints key value

    myRef.addListenerForSingleValueEvent(new ValueEventListener() {
        String d;
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // do some stuff once, could put into add button, save place, etc
            //since called once, data will be retrieved once.
            Gson json = new Gson();
            e = dataSnapshot.child(userID).getValue().toString();
            d = dataSnapshot.child(userID).getKey().toString();
            Log.d("STATE", "onDataChange: "+e+d);
            prints = dataSnapshot.getValue().toString();
            java.lang.reflect.Type type = new TypeToken<HashMap<String, String>>(){}.getType();
            HashMap<String, String> testHashMap2 = json.fromJson(e, type);

            for (String key : testHashMap2.keySet()) {
                Log.d("STATE","key: " + key + " value: " + testHashMap2.get(key));
                //textIn.setText(key);
                //nfcUrl = testHashMap2.get(key);
                //buttonAdd.performClick();
                // generate Buttons
            }
            Gson gson = new Gson();
            String hashMapString = gson.toJson(map);
            Log.d("STATE",hashMapString);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
    Log.d("STATE", e); //THIS LINE RETURNS NULL AND I DONT KNOW WHY!! Should e not get 
                       //updated since onDataChange is executed?
}

答案 2 :(得分:0)

使用sorted按索引1排序:

input = [['3', 2],['2370447', 282],['5300058', 610],['81615', 615],['3294332', 624],['3078798', 624],['1804986', 643]]
output = []
for i, x in enumerate(sorted(input, key=itemgetter(1))):
    x[1] = i
    output.append(x)

又矮又甜。

[['3', 0], ['2370447', 1], ['5300058', 2], ['81615', 3], ['3294332', 4], ['3078798', 5], ['1804986', 6]]

答案 3 :(得分:0)

使用内置排序功能可以轻松解决此问题

input_data = [['3', 2], ['2370447', 282], ['5300058', 610], ['81615', 615], ['3294332', 624], ['3078798', 624], ['1804986', 643]]

input_data.sort(key = lambda x: int(x[0]))
result = input_data.copy()
for i in range(len(result)):
    result[i][1] = i

print(result)

"""
output 
[['3', 0], ['81615', 1], ['1804986', 2], ['2370447', 3], ['3078798', 4], ['3294332', 5], ['5300058', 6]]
"""

答案 4 :(得分:0)

据我了解,您没有在5和6处获得相同元素索引的主要原因是因为更新列表时您的代码没有进入elif语句

with value 
    sortedCounts[i][1] = i-1

这将更改列表。

因此,与其直接更改列表,不如创建一个变量来将其更改并将其附加到新列表中。

    newList = []
    for i in range(len(sortedCounts)):
        if i == 0:
            variable = 0
        elif sortedCounts[i][1] == sortedCounts[i-1][1]:
            variable = i-1
        else: 
            variable = i
        newList.append([sortedCounts[i][0], variable])